title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
C: using realloc for high performance with an array of structs
|
<p>I am using realloc to adjust the size of an array of structs containing 3 points x, y and z. This struct is encapsulated inside another struct that contains the array, the length of the array and a "reserved" value that is used for a pre-allocation strategy for even faster performance when it is evident that more structs of points will be appended to the struct array.<br>
I am compiling with a Makefile that looks like this:</p>
<pre><code>CFLAGS = -g -Wall
LIBS = -lm
default: echo "You must specify a target, e.g. file1, file2"
file2:
gcc $(CFLAGS) -o $@ test.c file2.c $(LIBS)
</code></pre>
<p>I have a function to initialize an empty array structure, one to reset the array to be empty and free any dynamically allocated memory, one to append a point to the end of the array and one to remove a point designated by the index value. </p>
<p>I am getting two errors that I cannot find the cause of. One is that my code returns a non-zero status code of 1 and the other is the length seems to be off by one when I append a few thousand points.<br>
I am letting the append function do all the work but if I should be allocating dynamic memory in initialization, please tell me so. I am pretty sure that my reset and remove functions are working as they are supposed to. Please take a look at append as well. </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <assert.h>
typedef struct point
{
int x, y, z;
} point_t;
typedef struct
{
// number of points in the array
size_t len;
// pointer to an array of point_t structs
point_t* points;
size_t reserved;
} point_array_t;
void point_array_initial( point_array_t* pa )
{
assert(pa);
pa->len = 0;
pa->reserved = 0;
pa->points=NULL;
}
void point_array_reset( point_array_t* pa )
{//just free the array and set pa to NULL
assert(pa);
pa->points = memset(pa->points, 0, sizeof(point_t)*(pa->len));
pa->len = 0;
pa->reserved=0;
free(pa->points);
pa->points=NULL;
}
int point_array_append( point_array_t* pa, point_t* p )
{
assert(pa);
assert(p);
if(pa == NULL)//something wrong with intialization or reset
{
return 1;
}
if(p == NULL)//nothing to append
{
return 1;
}
//append the first point
if(pa->len == 0)
{
pa->len=1;
pa->reserved=pa->len*2;
pa->points = malloc(sizeof(point_t)* (pa->reserved));
if(pa->points == NULL)//malloc failed
{
return 1;
}
pa->points[pa->len-1].x = p->x;
pa->points[pa->len-1].y = p->y;
pa->points[pa->len-1].z = p->z;
}
if (pa->reserved > pa->len )
{
pa->len+=1;
pa->points[pa->len-1].x = p->x;//insert at index 0
pa->points[pa->len-1].y = p->y;
pa->points[pa->len-1].z = p->z;
}
//when we run out of space in reserved (len has caught up)
else if(pa->reserved == pa->len)
{
pa->len+=1;
pa->reserved=pa->len*2;
pa->points=realloc(pa->points, sizeof(point_t)*(pa->reserved));//doubling size of array
pa->points[pa->len-1].x = p->x;//TODO: change formula to find insertion point
pa->points[pa->len-1].y = p->y;
pa->points[pa->len-1].z = p->z;
}
return 0;
}
int point_array_remove( point_array_t* pa, unsigned int i )
{
assert(pa);
if (i >= pa->len)//out of bounds
{
return 1;
}
if(pa->len==0)//0 elements trying to remove from empty array
{
//pa->len=0;
//free(pa->points);
//pa->points=NULL;
return 1;
}
else if(pa->len ==1)//remove only element
{
pa->len-=1;//no copying required, just shorten
pa->points=realloc(pa->points, sizeof(point_t)*(pa->len));
//free(pa->points);
//pa->points=NULL;
}
else//array size is longer than 1 or 0
{
pa->points[i].x = pa->points[pa->len-1].x;
pa->points[i].y = pa->points[pa->len-1].y;
pa->points[i].z = pa->points[pa->len-1].z;
pa->len-= 1;//shorten array size
pa->reserved = pa->len*2;
pa->points=realloc(pa->points, sizeof(point_t)*(pa->len));//could reallocate for reserve here to increase speed.
}
return 0;
}
</code></pre>
| 3 | 2,100 |
Shared Compass/Lucene Index in JDBC Store
|
<p>Using the searchable plugin in Grails (which uses Compass/Lucene under the hood) we're trying to share a search index between two different web applications. One application accesses the data only in a read-only fashion. The other application allows to modify the data and is in charge of updating the index on any change or do a full re-index on demand.</p>
<p>To store the index we're using the JDBC Store (with both applications pointing to the same DB) <a href="http://www.compass-project.org/docs/latest/reference/html/core-connection.html" rel="nofollow">http://www.compass-project.org/docs/latest/reference/html/core-connection.html</a>.</p>
<p>Unfortunately, as soon as we rebuild the whole index in one application, the other application seems to have invalid data cached and an exception is thrown if a search is performed:</p>
<pre><code>| Error 2012-05-30 09:22:07,560 [http-bio-8080-exec-8] ERROR errors.GrailsExceptionResolver - IndexOutOfBoundsException occurred when processing request: [POST] /search
Index: 45, Size: 13. Stacktrace follows:
Message: Index: 45, Size: 13
Line | Method
->> 547 | RangeCheck in java.util.ArrayList
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 322 | get in ''
| 265 | fieldInfo . in org.apache.lucene.index.FieldInfos
| 254 | fieldName in ''
| 86 | read . . . in org.apache.lucene.index.TermBuffer
| 127 | next in org.apache.lucene.index.SegmentTermEnum
| 158 | scanTo . . in ''
| 271 | get in org.apache.lucene.index.TermInfosReader
| 332 | terms . . . in ''
| 717 | terms in org.apache.lucene.index.SegmentReader
| 93 | generate . in org.apache.lucene.search.PrefixGenerator
| 58 | getDocIdSet in org.apache.lucene.search.PrefixFilter
| 116 | <init> . . in org.apache.lucene.search.ConstantScoreQuery$ConstantScorer
| 81 | scorer in org.apache.lucene.search.ConstantScoreQuery$ConstantWeight
| 230 | scorer . . in org.apache.lucene.search.BooleanQuery$BooleanWeight
| 131 | search in org.apache.lucene.search.IndexSearcher
| 112 | search . . in ''
| 204 | search in org.apache.lucene.search.MultiSearcher
| 113 | getMoreDocs in org.apache.lucene.search.Hits
| 90 | <init> in ''
| 61 | search . . in org.apache.lucene.search.Searcher
| 146 | findByQuery in org.compass.core.lucene.engine.transaction.support.AbstractTransactionProcessor
| 259 | doFind . . in org.compass.core.lucene.engine.transaction.readcommitted.ReadCommittedTransactionProcessor
| 246 | find in org.compass.core.lucene.engine.transaction.support.AbstractConcurrentTransactionProcessor
| 352 | find . . . in org.compass.core.lucene.engine.LuceneSearchEngine
| 188 | hits in org.compass.core.lucene.engine.LuceneSearchEngineQuery
| 199 | hits . . . in org.compass.core.impl.DefaultCompassQuery
| 104 | doInCompass in grails.plugin.searchable.internal.compass.search.DefaultSearchMethod$SearchCompassCallback
| 133 | execute . . in org.compass.core.CompassTemplate
| 57 | doInCompass in grails.plugin.searchable.internal.compass.support.AbstractSearchableMethod
| 66 | invoke . . in grails.plugin.searchable.internal.compass.search.DefaultSearchMethod
| 37 | search in grails.plugin.searchable.SearchableService
</code></pre>
<p>We could communicate the fact that the index is rebuilt from one to the other application so that some clean-up could be performed.</p>
<ul>
<li>Did anybody have a similar problem with Grails and the Searchable plugin?</li>
<li>Is it possible to discard data cached by Compass/Lucene?</li>
<li>Is it possible to disable caching generally?</li>
</ul>
| 3 | 1,306 |
My map function is not working in react js
|
<pre><code>import React, { Component } from "react";
import { TextField } from "@material-ui/core";
import SearchResult from "./SearchResult";
class Search extends Component {
constructor() {
super();
this.state = {
data: [],
};
this.renderRes = this.renderRes.bind(this);
}
handelTextFieldChange(e) {
fetch(`http://localhost:8000/api/search-post?query=${e.target.value}`)
.then((res) => res.json())
.then((data) => {
this.setState({
data: data,
});
console.log(this.state.data);
});
}
renderRes() {
return (
<div>
{Array(this.state.data).map((_, index, blog) => {
return (
<SearchResult
content={blog[index]["body"]}
date={String(blog[index]["date"])}
author={blog[index]["author"]}
title={blog[index]["title"]}
/>
);
})}
</div>
);
}
render() {
return (
<div id="search">
<div className="search-box">
<TextField
id="outlined-basic"
label="Enter any Keyword"
variant="outlined"
onChange={(e) => this.handelTextFieldChange(e)}
/>
</div>
<div className="search-results">{this.renderRes()}</div>
</div>
);
}
}
export default Search;
</code></pre>
<p>My fetch data ---></p>
<pre><code>[
{"author": "Pranav Tripathi",
"title": "What is Diet?", "body": "In nutrition, diet is the sum of food consumed by a person or other organism.[1] The word diet often implies specific nutrition intake for health or weight-management reasons (with the two often being related). Although humans are omnivores, each culture and each person holds some food preferences or some food taboos. This may be due to personal tastes or ethical reasons. Individual dietary choices may be more or less healthy. Complete nutrition requires ingestion and absorption of vitamins, minerals, essential amino acids from protein and essential fatty acids from fat-containing food, also food energy in the form of carbohydrates, protein, and fat. Dietary habits and choices play a significant role in the quality of life, health, and longevity.",
"date": "2021-05-23 21:15:13.603332+00:00",
"post_id": "ABCDEF"}
]
</code></pre>
<p>There is more of it but I am sending the first one because others are mostly the same.</p>
<p>When I was debugging. It mostly gives undefined.
I have made the API in Django. From the backend side, it works well. But from the front end, it doesn't. I am fresher in react I am making the project to learn it, therefore, the react code is not industry standard</p>
| 3 | 1,281 |
Near Protocol NFT add string values mapped to a TokenId. i.e. tokenizing an ipfs hash
|
<p>I am trying to learn how to use the Near protocol and Rust by recreating my NFT Dapp which mapped string values (ipfs hash's to be exact) which I call a "sketch".
I have already done this successfully using Solidity on Ethereum. example shown at bottom of this page.</p>
<p><strong>I am simply trying to map string values to a tokenId and subsequently an OwnerId. I have used the boilerplate NFT lib.rs found on the <a href="https://examples.near.org/NFT" rel="nofollow noreferrer">Near dev NFT website</a> and have added my own string mapping for collections of "sketch" which will just contain an ipfs hash value to be used later on the front-end as an image source. What I have for lib.rs is below.</strong></p>
<pre><code> #![deny(warnings)]
use borsh::{BorshDeserialize, BorshSerialize};
use near_sdk::collections::{ TreeMap, UnorderedMap, UnorderedSet };
use near_sdk::{env, near_bindgen, AccountId};
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
pub trait NEP4 {
// Grant the access to the given `accountId` for the given `tokenId`.
// Requirements:
// * The caller of the function (`predecessor_id`) should have access to the token.
fn grant_access(&mut self, escrow_account_id: AccountId);
// Revoke the access to the given `accountId` for the given `tokenId`.
// Requirements:
// * The caller of the function (`predecessor_id`) should have access to the token.
fn revoke_access(&mut self, escrow_account_id: AccountId);
// Transfer the given `tokenId` to the given `accountId`. Account `accountId` becomes the new owner.
// Requirements:
// * The caller of the function (`predecessor_id`) should have access to the token.
fn transfer_from(&mut self, owner_id: AccountId, new_owner_id: AccountId, token_id: TokenId);
// Transfer the given `tokenId` to the given `accountId`. Account `accountId` becomes the new owner.
// Requirements:
// * The caller of the function (`predecessor_id`) should be the owner of the token. Callers who have
// escrow access should use transfer_from.
fn transfer(&mut self, new_owner_id: AccountId, token_id: TokenId);
// Returns `true` or `false` based on caller of the function (`predecessor_id) having access to the token
fn check_access(&self, account_id: AccountId) -> bool;
// Get an individual owner by given `tokenId`.
fn get_token_owner(&self, token_id: TokenId) -> String;
}
/// The token ID type is also defined in the NEP
pub type TokenId = u64;
pub type AccountIdHash = Vec<u8>;
// Begin implementation
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct NonFungibleTokenBasic {
pub token_to_account: UnorderedMap<TokenId, AccountId>,
pub account_gives_access: UnorderedMap<AccountIdHash, UnorderedSet<AccountIdHash>>, // Vec<u8> is sha256 of account, makes it safer and is how fungible token also works
pub owner_id: AccountId,
pub sketch: TreeMap<TokenId, String>
}
impl Default for NonFungibleTokenBasic {
fn default() -> Self {
panic!("NFT should be initialized before usage")
}
}
#[near_bindgen]
impl NonFungibleTokenBasic {
#[init]
pub fn new(owner_id: AccountId) -> Self {
assert!(env::is_valid_account_id(owner_id.as_bytes()), "Owner's account ID is invalid.");
assert!(!env::state_exists(), "Already initialized");
Self {
token_to_account: UnorderedMap::new(b"token-belongs-to".to_vec()),
account_gives_access: UnorderedMap::new(b"gives-access".to_vec()),
owner_id,
sketch: TreeMap::new(b"sketch".to_vec()),
}
}
}
#[near_bindgen]
impl NonFungibleTokenBasic {
/// Creates a token for owner_id, doesn't use autoincrement, fails if id is taken
/// example input for sketch is an ipfs hash ("QmdMuGrMCfvgwg7F6WM8CHev9PJxQ2n3f49ttSGuYfK4Qp")
pub fn mint_token(&mut self, owner_id: String, token_id: TokenId, sketch: String) {
// make sure that only the owner can call this funtion
self.only_owner();
// Since Map doesn't have `contains` we use match
let token_check = self.token_to_account.get(&token_id);
if token_check.is_some() {
env::panic(b"Token ID already exists.")
}
// No token with that ID exists, mint and add token to data structures
self.token_to_account.insert(&token_id, &owner_id, &sketch);
}
/// helper function determining contract ownership
fn only_owner(&mut self) {
assert_eq!(env::predecessor_account_id(), self.owner_id, "Only contract owner can call this method.");
}
}
fn transfer(&mut self, new_owner_id: AccountId, token_id: TokenId, sketch: String) {
let token_owner_account_id = self.get_token_owner(token_id);
let predecessor = env::predecessor_account_id();
if predecessor != token_owner_account_id {
env::panic(b"Attempt to call transfer on tokens belonging to another account.")
}
self.token_to_account.insert(&token_id, &new_owner_id, &sketch);
}
</code></pre>
<p>If it is any consolation, what I did in Solidity was map "sketch" as strings and push their value while adding the token Id based on the sketch array's length through to the ERC721.sol contract as shown below:</p>
<pre><code>
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Sketch is ERC721, Ownable{
address payable private admin;
string[] public sketchs;
mapping(string => bool) _sketchExists;
constructor() ERC721("Sketch", "SKETCH") public {
admin = msg.sender;
}
/// @notice mints the ipfs hash passed from the console
/// @dev example input for _sketch is an ipfs hash ("QmdMuGrMCfvgwg7F6WM8CHev9PJxQ2n3f49ttSGuYfK4Qp")
function mint(string memory _sketch) public {
require(!_sketchExists[_sketch]);
sketchs.push(_sketch);
uint _id = sketchs.length - 1;
_safeMint(msg.sender, _id,'');
_sketchExists[_sketch] = true;
}
function transfersketch(address _to, uint _id) public {
safeTransferFrom(msg.sender, _to, _id);
}
}
</code></pre>
<p>Am I in the right direction? Any help would be really appreciated. Thanks in advance!</p>
| 3 | 2,804 |
How to filter rows with non ascii encoding characters?
|
<p>I am dealing with Chinese characters excel. After I read the excel using</p>
<pre><code>data = pd.read_excel(file, encoding = 'utf-8')
</code></pre>
<p>, I can print the file normally (I can read the character).</p>
<p>But, when I want to filter the rows by a value, I got the following error:</p>
<p><code>Index = data[data[cols[0]] == "企业下属店铺销售记录"]]</code></p>
<pre><code>UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
</code></pre>
<p>I also tried <code>Index = data[data[cols[0] == u"企业下属店铺销售记录".encode(encoding = 'UTF-8)]]</code></p>
<p>But it returns empty dataframe</p>
<p>P.S: I also added <code># - *- coding: utf- 8 - *-</code> at the beginning of the python file</p>
<pre><code>This is the return of data.iloc[:, 0]
: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
result = libops.scalar_compare(x, y, op)
1 NaN
2 企业信息
4 企业名称
5 客户分层
6 企业下属店铺名称
8 店铺名称
9 名品城海外专营店
10 anmum海外旗舰店
11 企业征信信息
13 近一年是否有欺诈与假货店铺处罚
14 企业下属店铺销售信息
16 最近30天日均销售金额
17 最近30天日均销售订单数
18 最近30天日均销售件数
19 企业下属店铺菜鸟仓库存信息
21 最近30天日均期末库存件数
22 最近30天日均入库件数
23 最近30天日均销售出库件数
24 最近30天平均周转天数
25 企业下属店铺销售记录
27 店铺名称
28 名品城海外专营店
29 名品城海外专营店
30 名品城海外专营店
31 名品城海外专营店
32 名品城海外专营店
33 名品城海外专营店
34 名品城海外专营店
35 名品城海外专营店
36 名品城海外专营店
...
54 货主名称
55 名品城海外专营店
56 名品城海外专营店
57 名品城海外专营店
58 名品城海外专营店
59 名品城海外专营店
60 名品城海外专营店
61 名品城海外专营店
62 名品城海外专营店
63 名品城海外专营店
64 名品城海外专营店
65 名品城海外专营店
66 名品城海外专营店
67 anmum海外旗舰店
68 anmum海外旗舰店
69 anmum海外旗舰店
70 anmum海外旗舰店
71 anmum海外旗舰店
72 anmum海外旗舰店
73 anmum海外旗舰店
74 anmum海外旗舰店
75 anmum海外旗舰店
76 anmum海外旗舰店
77 anmum海外旗舰店
78 anmum海外旗舰店
79 企业评分
81 店铺名称
82 最终得分
84 店铺名称
85 最终得分
Name: 菜鸟金融客户授信初审报告(机密), Length: 76, dtype: object
</code></pre>
| 3 | 2,386 |
Listview button click throws null pointer exception
|
<p>Inside my <code>UpdateSupervitionActivity</code> class <code>CallAdapter()</code> method is called to generate the <code>listview</code>. The <code>listview</code> has a button for each <code>item</code> to remove an <code>item</code>. After the <code>listview</code> is loaded, when I try to remove an item from the <code>listview</code> by clicking the listview button, it throws a <code>nullpointer</code> exception and the app crashes.</p>
<p><br><strong>Java class with CallAdapter() method</strong>:<br/></p>
<pre><code>package bd.edu.bubt.regup;
public class UpdateSupervitionActivity extends AppCompatActivity {
EditText fac_code, s_intake, s_section;
ListView listView;
Button search, addlist, update;
Spinner shift;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_supervition);
fac_code = (EditText) findViewById(R.id.sh_code);
s_intake = (EditText) findViewById(R.id.intake);
s_section = (EditText) findViewById(R.id.section);
listView = (ListView) findViewById(R.id.faclistview);
shift = (Spinner) findViewById(R.id.shift);
addlist = (Button) findViewById(R.id.addlist);
search = (Button) findViewById(R.id.search);
update = (Button) findViewById(R.id.update);
}
public void CallAdapter(Context context)
{
adapterlist.clear();
if(daylist.size() == 0)
{
//no intake list for day shift
if(evelist.size() == 0)
{
//no intake list for evening shift
}
else if(evelist.size() > 0)
{
for (int i=0;i<evelist.size();i++)
{
String s = evelist.get(i);
int p = s.indexOf("-");
String intake = s.substring(0,p);
String section = s.substring(p+1,s.length());
adapterlist.add(new UpdateSupervisionItem(intake, section, "Evening"));
}
}
}
else if(daylist.size() > 0)
{
for (int i=0;i<daylist.size();i++)
{
String s = daylist.get(i);
int p = s.indexOf("-");
String intake = s.substring(0,p);
String section = s.substring(p+1,s.length());
adapterlist.add(new UpdateSupervisionItem(intake, section, "Day"));
}
if(evelist.size() == 0)
{
//no intake list for evening shift
}
else if(evelist.size() > 0)
{
for (int i=0;i<evelist.size();i++)
{
String s = evelist.get(i);
int p = s.indexOf("-");
String intake = s.substring(0,p);
String section = s.substring(p+1,s.length());
adapterlist.add(new UpdateSupervisionItem(intake, section, "Evening"));
}
}
}
UpdateSupervisionAdapter updateSupervisionAdapter = new UpdateSupervisionAdapter(context, R.layout.update_supervision_list_view_layout, adapterlist);
listView.setAdapter(updateSupervisionAdapter);
}
}
</code></pre>
<p><br><strong>Adapter class:</strong><br/></p>
<pre><code>package bd.edu.bubt.regup;
public class UpdateSupervisionAdapter extends ArrayAdapter<UpdateSupervisionItem> {
ArrayList<UpdateSupervisionItem> adapterlist = new ArrayList<>();
Context context;
public UpdateSupervisionAdapter(Context context, int textViewResourceId, ArrayList<UpdateSupervisionItem> objects) {
super(context, textViewResourceId, objects);
this.context = context;
adapterlist = objects;
}
@Override
public int getCount() {
return super.getCount();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent){
View v = convertView;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.update_supervision_list_view_layout, null);
TextView intake = (TextView) v.findViewById(R.id.intake);
TextView section = (TextView) v.findViewById(R.id.section);
TextView shift = (TextView) v.findViewById(R.id.shift);
final Button remove = (Button) v.findViewById(R.id.remove);
remove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.blink_anim);
remove.startAnimation(animation);
UpdateSupervisionItem updateSupervisionItem = getItem(position);
String in_take = updateSupervisionItem.getIntake();
String sec_tion = updateSupervisionItem.getSection();
String shi_ft = updateSupervisionItem.getShift();
UpdateSupervitionActivity updateSupervitionActivity = new UpdateSupervitionActivity();
if(TextUtils.equals(shi_ft,"Day"))
{
updateSupervitionActivity.daylist.remove(in_take+ "-" +sec_tion);
updateSupervitionActivity.CallAdapter(context);
}
else if(TextUtils.equals(shi_ft,"Evening"))
{
updateSupervitionActivity.evelist.remove(in_take+ "-" +sec_tion);
updateSupervitionActivity.CallAdapter(context);
}
}
});
intake.setText("Intake: " +adapterlist.get(position).getIntake());
section.setText("Section: " +adapterlist.get(position).getSection());
shift.setText("Shift: " +adapterlist.get(position).getShift());
return v;
}
}
</code></pre>
<p><br><strong>Error log:</strong><br/></p>
<pre><code>FATAL EXCEPTION: main
Process: bd.edu.bubt.regup, PID: 31219
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at bd.edu.bubt.regup.UpdateSupervitionActivity.CallAdapter(UpdateSupervitionActivity.java:352)
at bd.edu.bubt.regup.UpdateSupervisionAdapter$1.onClick(UpdateSupervisionAdapter.java:70)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code></pre>
| 3 | 3,325 |
Angular 5 - How to dynamically add event on a DOM element?
|
<p>I'm try to implement a search input as the one on "Medium" website by adding a new suggestion (based on the input context for full text search) at the top of the list of the current suggestions. I'm on an angular 5 project and I use typeahead for research module. </p>
<p>So this is how I add new suggestion on top off typeahead list:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var nba = [{
"team": "Boston Celtics"
}, {
"team": "Dallas Mavericks"
}, {
"team": "Brooklyn Nets"
}, {
"team": "Houston Rockets"
}, {
"team": "New York Knicks"
}, {
"team": "Memphis Grizzlies"
}, {
"team": "Philadelphia 76ers"
}, {
"team": "New Orleans Hornets"
}, {
"team": "Toronto Raptors"
}, {
"team": "San Antonio Spurs"
}];
var teams = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: nba
});
var search = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: [{
'team': 'xxxxx'
}]
});
$('#multiple-datasets .typeahead').typeahead({
highlight: true,
hint: false,
minlenght: 2
},
{
name: 'search-in-team',
display: 'team',
source: teams,
templates: {
header: '<div class="group">Teams</div>'
}
});
$('.typeahead').bind('typeahead:render', (event, suggestions, async, dataset) => {
$('.tt-dataset').prepend('<div class="tt-suggestion tt-selectable added" > <span class="strong"> Search for "' + $('.typeahead').val() + '"</span></div>');
});
$('.typeahead').bind('typeahead:select', (ev, suggestion) => {
alert(suggestion.team)
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.group {
padding: .5rem .5rem 0rem .5rem;
font-family: $avenir_next;
color: $color-47;
border-bottom: 1px solid grey;
font-weight: bold;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<div id='multiple-datasets'>
<input type="text" id="sskSearch" class="typeahead" placeholder="Search">
</div></code></pre>
</div>
</div>
</p>
<p>I have an alert when I click on the suggestion under "Teams", But nothing happen when click on the new first element I manually added ("Search for 'xxxx').
<a href="https://i.stack.imgur.com/EWMRq.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Any help Please!!!</p>
| 3 | 1,067 |
Slow reading from CSV file
|
<p>I'm trying to read from a csv file but it's slow. Here's the code roughly explained:</p>
<pre><code>private static Film[] readMoviesFromCSV() {
// Regex to split by comma without splitting in double quotes.
// https://regexr.com/3s3me <- example on this data
var pattern = Pattern.compile(",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)");
Film[] films = null;
try (var br = new BufferedReader(new FileReader(FILENAME))) {
var start = System.currentTimeMillis();
var temparr = br.lines().skip(1).collect(Collectors.toList()); // skip first line and read into List
films = temparr.stream().parallel()
.map(pattern::split)
.filter(x -> x.length == 24 && x[7].equals("en")) // all fields(total 24) and english speaking movies
.filter(x -> (x[14].length() > 0)) // check if it has x[14] (date)
.map(movieData -> new Film(movieData[8], movieData[9], movieData[14], movieData[22], movieData[23], movieData[7]))
// movieData[8] = String title, movieData[9] = String overview
// movieData[14] = String date (constructor parses it to LocalDate object)
// movieData[22] = String avgRating
.toArray(Film[]::new);
System.out.println(MessageFormat.format("Execution time: {0}", (System.currentTimeMillis() - start)));
System.out.println(films.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return films;
}
</code></pre>
<p>File is about 30 MB big and it takes about 3-4 seconds avg. I'm using streams but it's still really slow. Is it because of that splitting each time?</p>
<p><strong>EDIT:</strong> I've managed to speed up reading and processing time by 3x with uniVocity-parsers library. On average it takes 950 ms to finish. That's pretty impressive.</p>
<pre><code>private static Film[] readMoviesWithLib() {
Film[] films = null;
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setLineSeparatorDetectionEnabled(true);
RowListProcessor rowProcessor = new RowListProcessor();
parserSettings.setProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);
CsvParser parser = new CsvParser(parserSettings);
var start = System.currentTimeMillis();
try {
parser.parse(new BufferedReader(new FileReader(FILENAME)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<String[]> rows = rowProcessor.getRows();
films = rows.stream()
.filter(Objects::nonNull)
.filter(x -> x.length == 24 && x[14] != null && x[7] != null)
.filter(x -> x[7].equals("en"))
.map(movieData -> new Film(movieData[8], movieData[9], movieData[14], movieData[22], movieData[23], movieData[7]))
.toArray(Film[]::new);
System.out.printf(MessageFormat.format("Time: {0}",(System.currentTimeMillis()-start)));
return films;
}
</code></pre>
| 3 | 1,247 |
How to append an element to a dynamically generated element
|
<p>I have several forms one clone after another depends on the user input. in each form I have button to add a row of input:</p>
<pre><code><h4>3.3.5 Input Parameters</h4>
<table id="input_param" data-role="table" class="ui-responsive table-stroke">
<thead>
<tr>
<th data-priority="1">Parameter</th>
<th data-priority="2">Data Type</th>
<th data-priority="3">Required</th>
<th data-priority="4">Brief description</th>
<th data-priority="5">Location in Request</th>
</tr>
</thead>
<tbody></tbody>
</table>
<input type="button" id="add_input_param" value="+ Add Input Parameter" data-inline="true" /><br />
</code></pre>
<p>so if it's the first form(static form) than this code will work:</p>
<pre><code>$("#add_input_param").click(function() {
var maincontent = loadParam('IP', '01', ipCount);
ipCount++;
$('#input_param').append(maincontent).trigger("create");
});
</code></pre>
<p>because the one after the first one I understand I have to use .on() </p>
<pre><code>$("#input_form").on("click", "#add_input_param", function() {
var maincontent = loadParam('IP', '01', ipCount);
ipCount++;
//$('this').append(maincontent).trigger("create");
});
</code></pre>
<p>the comment area is the part that I cannot get it work. I would like to append the maincontent to #input_param (it's a table), but because it's dynamically generated how can I modify that line of code so it will work with it?</p>
<p>maincontent will be something like this:</p>
<pre><code>function loadParam(IO, form_number, counter) {
var id = IO + form_number + '-' + counter;
var maincontent = '<tr>';
maincontent += '<th><input type="text" name="param' + id + '" id="param' + id + '" value="" /></th>';
maincontent += '<td><input type="text" name="data_type' + id + '" id="data_type' + id + '" /></td>';
maincontent += '<td>';
maincontent += '<select id="required" name="req' + id + '" id="req' + id + '"class="form-alpha">';
maincontent += '<option value="Mandatory" >Mandatory</option>';
maincontent += '<option value="Optional" >Optional</option>';
maincontent += '<option value="Conditional" >Conditional</option>';
maincontent += '</select>';
maincontent += '</td>';
maincontent += '<td><textarea name="des' + id + '" id="des' + id + '" ></textarea></td>';
maincontent += '<td>';
maincontent += '<select name="location' + id + '" id="location' + id + '" class="form-alpha">';
maincontent += '<option value="Header" >Header</option>';
maincontent += '<option value="Body" >Body</option>';
maincontent += '<option value="Query_param" >Query Parameter</option>';
maincontent += '<option value="Resource_uri" >Resource URI</option>';
maincontent += '</select>';
maincontent += '</td>';
maincontent += '</tr>';
return maincontent;
}
</code></pre>
| 3 | 1,358 |
Error while running JDBC on postgres
|
<p>This is my CreateQuery.java class .</p>
<pre><code>package DbConnect;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CreateQuery {
Connection conn;
public CreateQuery() throws ClassNotFoundException, SQLException, IOException {
conn=new DbAccess().returnDatabaseConnection();
}
public int addNewLayertoDB(){
try {
PreparedStatement statement = null;
//String table_name = feature_name + "_" + shape;
String query = "SELECT the_geom from bbmp ";
statement = conn.prepareStatement(query);
//statement.setString(1, feature_name);
ResultSet rs = statement.executeQuery();
rs.close();
return 1;
} catch (SQLException ex) {
System.out.println("Sql exception");
return 0;
}
}
public void closeConn() throws SQLException {
if (conn != null) {
this.conn.close();
}
}
public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{
CreateQuery cq = new CreateQuery();
cq.addNewLayertoDB();
cq.closeConn();
}
}
</code></pre>
<p>This is my DbConnect class </p>
<pre><code>package DbConnect;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class DbAccess{
public static void main(String[] argv) {
System.out.println("-------- PostgreSQL " +
"JDBC Connection Testing ------------");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/Ethermap","postgres", "*******");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null){
System.out.println("You made it, take control your database now!");
}else{
System.out.println("Failed to make connection!");
}
}
public Connection returnDatabaseConnection() {
System.out.println("DB not connected");
return null;
}
}
</code></pre>
<p>The error I am getting when I run CreateQuery is </p>
<pre><code>DB not connected
Exception in thread "main" java.lang.NullPointerException
at DbConnect.CreateQuery.addNewLayertoDB(CreateQuery.java:24)
at DbConnect.CreateQuery.main(CreateQuery.java:45)
</code></pre>
<p>What is the error ? And How do I debug it ?</p>
| 3 | 1,439 |
Java reflection vs non reflection performance comparison
|
<p>So I tried to test the performance of java reflection. I want to add every value of every field in a class into a map.</p>
<pre><code> public static class testClass {
String monday = "Monday";
String tuesday = "Tuesday";
String wednesday = "Wednesday";
String thursday = "Thursday";
String friday = "Friday";
String saturday = "Saturday";
String sunday = "Sunday";
... getter and setters ...
}
public static void main(String args[]) {
noReflection();
reflection();
}
public static void noReflection() {
testClass test = new testClass();
long start = System.nanoTime();
Map myMap = new HashMap<>();
for (int i = 0; i < RUNS; i++) {
List<Integer> myList = new ArrayList<>();
for(myDayz days: myDayz.values()) {
myList.add(days.ordinal());
}
myMap.put(myList.get(0),test.getMonday());
myMap.put(myList.get(1),test.getFriday());
myMap.put(myList.get(2),test.getSaturday());
myMap.put(myList.get(3),test.getSunday());
myMap.put(myList.get(4),test.getThursday());
myMap.put(myList.get(5),test.getTuesday());
myMap.put(myList.get(6),test.getWednesday());
myMap.clear();
}
System.out.printf("no reflection: %,d ns%n", (System.nanoTime() - start)/RUNS);
}
public static void reflection() {
testClass as = new testClass();
long start = System.nanoTime();
final String stringClassName = String.class.getName();
Map myMap = new HashMap<>();
for (int i = 0; i < RUNS; i++) {
int enumIndex = 0;
List<Integer> myList = getEnumsAsList(myDayz.class);
for(Field field : as.getClass().getDeclaredFields()) {
field.setAccessible(true);
String fieldTypeName = field.getGenericType().getTypeName();
try {
Object instance = field.get(as);
if (instance != null && fieldTypeName.equals(stringClassName)) {
myMap.put(myList.get(enumIndex),(String) instance);
enumIndex++;
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
myMap.clear();
}
System.out.printf("reflection: %,d ns%n", (System.nanoTime() - start)/RUNS);
}
private static <E extends Enum<E>> List<Integer> getEnumsAsList(Class<E> eClass) {
List<Integer> enumOrdinals = new ArrayList<>();
for (E en : EnumSet.allOf(eClass))
{
enumOrdinals.add(en.ordinal());
}
return enumOrdinals;
}
private enum myDayz {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
</code></pre>
<p>Now what suprised me is that the non reflection code is about ~60% faster. I thought it would be ALOT faster. My question is if this is what you can expect or have i done something wrong here?</p>
| 3 | 1,350 |
Why does the Oracle database query (Long datatype in Oracle database table's column) not execute in QueryDatabaseTable Apache Nifi?
|
<p>I have a Oracle database with a column setup as '<code>long</code>' data type. The column has <code>XML</code> data. I am trying to transfer the data from Oracle to Bigquery.</p>
<p>I tried the following setup and it worked perfectly: </p>
<pre><code>ExecuteSQL -> AvroToJson ->PutBigQueryBatch
</code></pre>
<p>However when I tried to do a incremental load with the following setup, it threw an error:</p>
<pre><code>QueryDatabaseTable -> AvroToJson ->PutBigQueryBatch
</code></pre>
<p>I tried to look into the issue and found the Github <a href="https://github.com/apache/nifi/commit/68a49cfad04df2f467f9529c0fc1b6daf1781192" rel="nofollow noreferrer">support request</a> which is resolved. Is this bug or is there a mistake I make?</p>
<p>Error: </p>
<pre><code>2020-01-14 19:24:56,184 ERROR [Timer-Driven Process Thread-41] o.a.n.p.standard.QueryDatabaseTable QueryDatabaseTable[id=016f11ea-e0e7-1523-fbf7-428dad259c96] Unable to execute SQL select query SELECT * FROM (select * from table) table due to org.apache.nifi.processor.exception.ProcessException: Error during database query or conversion of records.: org.apache.nifi.processor.exception.ProcessException: Error during database query or conversion of records.
org.apache.nifi.processor.exception.ProcessException: Error during database query or conversion of records.
at org.apache.nifi.processors.standard.AbstractQueryDatabaseTable.lambda$onTrigger$0(AbstractQueryDatabaseTable.java:295)
at org.apache.nifi.controller.repository.StandardProcessSession.write(StandardProcessSession.java:2730)
at org.apache.nifi.processors.standard.AbstractQueryDatabaseTable.onTrigger(AbstractQueryDatabaseTable.java:291)
at org.apache.nifi.controller.StandardProcessorNode.onTrigger(StandardProcessorNode.java:1176)
at org.apache.nifi.controller.tasks.ConnectableTask.invoke(ConnectableTask.java:213)
at org.apache.nifi.controller.scheduling.TimerDrivenSchedulingAgent$1.run(TimerDrivenSchedulingAgent.java:117)
at org.apache.nifi.engine.FlowEngine$2.run(FlowEngine.java:110)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.nifi.processor.exception.ProcessException: java.sql.SQLException: Stream has already been closed
at org.apache.nifi.processors.standard.sql.DefaultAvroSqlWriter.writeResultSet(DefaultAvroSqlWriter.java:51)
at org.apache.nifi.processors.standard.AbstractQueryDatabaseTable.lambda$onTrigger$0(AbstractQueryDatabaseTable.java:293)
... 13 common frames omitted
Caused by: java.sql.SQLException: Stream has already been closed
at oracle.jdbc.driver.LongAccessor.getBytesInternal(LongAccessor.java:156)
at oracle.jdbc.driver.LongAccessor.getBytes(LongAccessor.java:126)
at oracle.jdbc.driver.LongAccessor.getString(LongAccessor.java:201)
at oracle.jdbc.driver.T4CLongAccessor.getString(T4CLongAccessor.java:450)
at oracle.jdbc.driver.CharCommonAccessor.getObject(CharCommonAccessor.java:788)
at oracle.jdbc.driver.OracleResultSetImpl.getObject(OracleResultSetImpl.java:1026)
at org.apache.commons.dbcp2.DelegatingResultSet.getObject(DelegatingResultSet.java:733)
at org.apache.commons.dbcp2.DelegatingResultSet.getObject(DelegatingResultSet.java:733)
at org.apache.nifi.util.db.JdbcCommon.convertToAvroStream(JdbcCommon.java:337)
at org.apache.nifi.processors.standard.sql.DefaultAvroSqlWriter.writeResultSet(DefaultAvroSqlWriter.java:49)
... 14 common frames omitted
</code></pre>
<p>I tried to set <code>Normalise Table/ Column Names</code> along with <code>Avro Logical Type</code> to both <code>True</code> and <code>False</code> in all four combinations, it still threw an error. Is there any known fix for this?</p>
| 3 | 1,440 |
How to debug with GDB on RT Linux: fails with SIGTRAP
|
<p>I am trying to debug a multi threaded application on RT Linux. On regular Linux, the app runs fine, and GDB also runs fine. On RT Linux the app runs fine, but under GDB, the app runs for several seconds then terminates and prints:</p>
<p><code>Program terminated with signal SIGTRAP, Trace/breakpoint trap. The program no longer exists.</code></p>
<p>I cannot do a backtrace, or determine what is causing the problem. I suspect it might be some libraries used by gdb, or else maybe memory corruption in the app.</p>
<p>I create over sixty threads, and many more are created by various watchdogs and timers.
What I have tried so far:</p>
<ol>
<li><p>Checking for mismatch between libpthread.so.0 and libthread_db.so.1. I used </p>
<p><code>objdump -s --section .comment /usr/lib64/libthread_db-1.0.so</code></p></li>
</ol>
<p>on both libraries, and they both gave the same version of gcc, which is the same gcc I am using to build the app </p>
<p><code>gcc --version gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-36)</code></p>
<ol start="2">
<li><p>Trying to set a catchpoint for SIGTRAP in gdb with</p>
<p><code>catch signal SIGTRAP
commands
p $_siginfo.si_code
end</code></p></li>
</ol>
<p>This did not alter behaviour of gdb at all.
Any ideas? New kernel libraries or sources that I should download?</p>
<p><strong>Versions:</strong>
My original linux was Scientific Linux 7 downloaded from the CERN repo (based on CentOS 7). I also downloaded and installed the prebuilt RT kernel from there.</p>
<p><code># gdb --version
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-114.el7</code></p>
<p><code># uname -r
3.10.0-957.10.1.rt56.921.el7.x86_64</code></p>
<p><code>gcc --version gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-36)</code></p>
<p><strong>Some Progress</strong>
Several times gdb itself crashed and left a gdb core dump. Backtracing into gdb using the core file, I found the same call stack -- last few functions shown below:</p>
<pre><code>(gdb) bt
#0 0x00007fc62ca9e207 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:55
#1 0x00007fc62ca9f8f8 in __GI_abort () at abort.c:90
#2 0x000000000069f5e6 in dump_core ()
#3 0x00000000006a1de5 in internal_vproblem ()
#4 0x00000000006a1e59 in internal_verror ()
#5 0x00000000006a1eff in internal_error ()
#6 0x00000000004d5149 in check_ptrace_stopped_lwp_gone ()
#7 0x00000000004d51e2 in linux_resume_one_lwp ()
#8 0x00000000004d6e44 in linux_handle_extended_wait ()
#9 0x00000000004d9cf9 in linux_nat_wait ()
#10 0x00000000004e1273 in thread_db_wait ()
#11 0x0000000000607602 in target_wait ()
#12 0x00000000005cf815 in wait_for_inferior ()
</code></pre>
<p>This seems to indicate a problem with gdb, so I rebuilt gdb using the latest source (8.2.1) and this stopped the gdb crashes. Now GDB stops at many kernel calls (sleep, semwait etc) with a SIGSTOP, I can press continue, but this makes debugging impractical.</p>
<p>If I add the following line to .gdbinit <code>handle SIGSTOP nostop noprint pass</code> then gdb does not stop at kernel calls, but now breakpoints don't work and it is very difficult to stop either gdb or the process being debugged.</p>
| 3 | 1,117 |
Python multiprocessing issue with arguments set/list completion of processes
|
<p>This other post is exactly, I think, regarding what i want to do.
<a href="https://stackoverflow.com/questions/5442910/python-multiprocessing-pool-map-for-multiple-arguments">Python multiprocessing pool.map for multiple arguments</a></p>
<p>How I am trying to implement is in my pseudo code:</p>
<h1>called by another function in my code</h1>
<pre><code>def find_similar(db, num, listofsets):
#db is the sqlite3 database
#num is a variable I need for the sql query
#listofsets - is a list of sets. each set is a set of strings
threshold = 0.49
similar_db_rows=[]
for row in db.execute("SELECT thing1, thing2, thing3 FROM table WHERE num !={n};".format(n=num)):
#thing3 is a long string, each value separated by a comma
items = set(row[3].strip().split(','))
for set_item in listofsets:
sim_score = sim_function(set_item, items)
if sim_score<threshold:
similar_db_rows.append(row)
return similar_db_rows
def sim_function(x,y):
#x is a set, and y is a second set. The function does some calculation
and comparing, then returns a float value
return float_value
</code></pre>
<p>This works. What I was trying to do was use multiprocessing on the 2nd for loop. Instead of iterating each set (as my list of sets can have a lot, and this is a major bottle neck) and calling the function, I wanted to use multiprocessing so that it would call the function for these sets, passing a set along with the second constant argument from the sqlquery, many at a time, then return the resulting number from each set into a list. After all of the sets have been processed, then I can use the items in that list to check if any item meets a threshold.</p>
<p>I tried to use the <code>func_star</code> and <code>pool.map(func_star, itertools.izip(a_args, itertools.repeat(second_arg)))</code> by Sebestian AND the `parmap' by zeehio. But for me, for example if I had 30 sets in the list, it was returning a list of results more than 30 times, each return it would check for similarity threshold, and appending rows, but never breaking out of this and I end up control Z'ing the whole thing.</p>
<p>Below is an example of what I attempted, first using parmap:</p>
<pre><code>def find_similar(db, num, listofsets):
#db is the sqlite3 database
#num is a variable I need for the sql query
#listofsets - is a list of sets. each set is a set of strings
threshold = 0.49
list_process_results=[]
similar_db_rows=[]
for row in db.execute("SELECT thing1, thing2, thing3 FROM table WHERE num !={n};".format(n=num)):
items = set(row[3].strip().split(','))
list_process_results = parmap.starmap(sim_function, zip(listofsets), items)
print list_process_results
if any(t < threshold for t in list_process_results):
#print "appending a row"
similar_db_rows.append(row)
return similar_db_rows
</code></pre>
<p>and <code>func_star</code>:</p>
<pre><code>def func_star(a_b):
"""Convert `f([1,2])` to `f(1,2)` call."""
return sim_function(*a_b)
def find_similar(db, num, listofsets):
pool = Pool()
#db is the sqlite3 database
#num is a variable I need for the sql query
#listofsets - is a list of sets. each set is a set of strings
threshold = 0.49
list_process_results=[]
similar_db_rows=[]
for row in db.execute("SELECT thing1, thing2, thing3 FROM table WHERE num !={n};".format(n=num)):
items = set(row[3].strip().split(','))
list_process_results=pool.map(func_star, itertools.izip(listofsets, itertools.repeat(items ) ))
print list_process_results
if any(t < threshold for t in list_process_results):
#print "appending a row"
similar_db_rows.append(row)
return similar_db_rows
</code></pre>
<p>The same is happening for me with both, it goes on forever, returning a list of the # I am expecting (a different set of values each time), "appending a row", and never breaking out.</p>
<p>Thanks for the help!!! extra is if multiprocessing can also be used for the results of the row query (the outer loop) but i will first conquer the inner loop</p>
<p>To answer Dano question about <code>find_similar</code>()---
I have another function that has a for loop. Each iteration of this for loop calls <code>find_similar</code>. When the resulting list is returned from <code>find_similar</code>, it prints the length of the list return, it then proceeds to finish the remainder of the loop, and go to the next for element. After this for loop is finished, the function is over, and <code>find_similiar</code> is not called again.</p>
| 3 | 1,627 |
Reading response text in Ajax using JQuery
|
<pre><code>function upload_file(){
var file =document.getElementById('computer_image').files[0];
if(file!==null){
if(file.type==='image/jpeg' ||
file.type==='image/png' ||file.type==='image/jpg'){
$('#progressbar').show();
var formData = new FormData();
formData.append("file1", file);
$.ajax({
url: 'file_upload/ImageUpload',
type: 'POST',
headers: {"abc": "aaaaaaaaa"},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandler, false);
}
return myXhr;
},
success: function( request,data, textstatus){
alert(textstatus.getResponseHeader('abc'));
},
error:errorHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
}
else {
alert('sorry we are not accepting file other than PNG , JPEG and JPG');
}
}
}
</code></pre>
<p>I am using CodeIgniter Framework .Below is my PHP code to Process a file . </p>
<pre><code>function ImageUpload(){
$status="";
if (empty($_FILES["file1"]))
{
$status = "sorry Something went wrong";
$this->output->set_status_header('400');
echo "sorry Something went wrong";
}
if ($status !== "sorry Something went wrong")
{
//call a function to get path name
$path="./upload";
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size' ] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['remove_spaces']=TRUE;
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
/* If directory doesn't exist than create a new .*/
if (!file_exists($path) && !is_dir($path)) {
mkdir($path);
}
/* If there is any error during upload */
if ( ! $this->upload->do_upload('file1')){
$this->output->set_status_header('400');
echo "sorry Something went wrong";
}
/*Image has been successfully Uploaded */
else{
$var = $this->upload->data('','');
echo $path.'/'.$var["file_name"].'='.$var["image_width"].
'='.$var["image_height"];
}
}
</code></pre>
<p>I have tried multiple flavor to get Response text but didn't success . What should be after complete to read response text .
getting <code>null</code> as output . </p>
| 3 | 1,640 |
Javascript calculator equal function failing
|
<p>I have created a calculator using JavaScript. When I chain together multiple math problems I get the answer I desire until I try and get the end result with the = button. When I do only two numbers the = button works perfectly fine. I have my code set up to set the a mathHoldOne and mathHoldTwo. Both contain a number and a boolean if its set or not. I have checked dev tools to see what the difference is between a problem with two numbers and a problem with 2+ numbers and I can't seem to find the issue. <a href="https://codepen.io/tchbell/full/WdjxdG/" rel="nofollow noreferrer">codepen</a></p>
<pre><code>const view = {
//Updates view when buttons are clicked
updateView: function () {
let viewScreen = document.getElementsByClassName('js-view')[0];
let miniView = document.getElementsByClassName('mini-view')[0];
viewScreen.innerHTML = '';
miniView.innerHTML = '';
const jsContainer = document.getElementsByClassName('js-container')[0];
jsContainer.addEventListener('click', function (e) {
let show = e.target.innerHTML;
viewScreen.innerHTML += show;
});
},
//have a handler that sets what each button does with event delegation
btnHandle: function () {
let mathType = {"type": undefined};
let mathHoldOne = {"num": 0, "set": false};
let mathHoldTwo = {"num": 0, "set": false};
let btnHandler = document.querySelector('.js-container');
btnHandler.addEventListener('click', function (event) {
let btn = event.target;
let screenValue = document.querySelector('.js-view');
let miniView = document.querySelector('.mini-view');
switch (btn.className) {
//clears whats in the view window
case('cell clear'):
screenValue.innerHTML = '';
miniView.innerHTML = '';
mathHoldOne.num = 0;
mathHoldOne.set = false;
mathHoldTwo.num = 0;
mathHoldTwo.set = false;
mathType.type = undefined;
break;
case('cell math multiply'):
//assigns mathHoldTwo.num if mathHoldOne.set is true and blanks the screenValue
if (mathHoldOne.set) {
mathHoldTwo.num = parseInt(screenValue.innerHTML);
mathHoldTwo.set = true;
screenValue.innerHTML = '';
//if mathHoldOne.set is false it assigns mathHoldOne.num and sets the set property to true
//also sets mathType.type to multiply
} else {
mathHoldOne.num = parseInt(screenValue.innerHTML);
mathHoldOne.set = true;
screenValue.innerHTML = '';
mathType.type = "mulitply";
}
if (mathHoldOne.set && mathHoldTwo.set) {
//if both numbers are set cycle through calcFunc to find which mathType.type matches
//and execute that function with the two values
for (let name in calcFunc) {
if (mathType.type === name) {
miniView.innerHTML = calcFunc[name](mathHoldOne.num, mathHoldTwo.num);
mathHoldOne.num = calcFunc[name](mathHoldOne.num, mathHoldTwo.num);
}
}
mathHoldTwo.num = 0;
mathHoldTwo.set = false;
mathType.type = 'multiply';
}
break;
case('cell math divide'):
if (mathHoldOne.set) {
mathHoldTwo.num = parseInt(screenValue.innerHTML);
mathHoldTwo.set = true;
screenValue.innerHTML = '';
} else {
mathHoldOne.num = parseInt(screenValue.innerHTML);
mathHoldOne.set = true;
screenValue.innerHTML = '';
mathType.type = "divide";
}
if (mathHoldOne.set && mathHoldTwo.set) {
for (let name in calcFunc) {
if (mathType.type === name) {
miniView.innerHTML = calcFunc[name](mathHoldOne.num, mathHoldTwo.num);
mathHoldOne.num = calcFunc[name](mathHoldOne.num, mathHoldTwo.num);
}
}
mathHoldTwo.num = 0;
mathHoldTwo.set = false;
mathType.type = 'divide';
}
break;
case('cell math add'):
if (mathHoldOne.set) {
mathHoldTwo.num = parseInt(screenValue.innerHTML);
mathHoldTwo.set = true;
screenValue.innerHTML = '';
} else {
mathHoldOne.num = parseInt(screenValue.innerHTML);
mathHoldOne.set = true;
screenValue.innerHTML = '';
mathType.type = "add";
}
if (mathHoldOne.set && mathHoldTwo.set) {
for (let name in calcFunc) {
if (mathType.type === name) {
miniView.innerHTML = calcFunc[name](mathHoldOne.num, mathHoldTwo.num);
mathHoldOne.num = calcFunc[name](mathHoldOne.num, mathHoldTwo.num);
}
}
;
mathHoldTwo.num = 0;
mathHoldTwo.set = false;
mathType.type = 'add';
}
break;
case('cell math subtract'):
if (mathHoldOne.set) {
mathHoldTwo.num = parseInt(screenValue.innerHTML);
mathHoldTwo.set = true;
screenValue.innerHTML = '';
} else {
mathHoldOne.num = parseInt(screenValue.innerHTML);
mathHoldOne.set = true;
screenValue.innerHTML = '';
mathType.type = "subract";
}
if (mathHoldOne.set && mathHoldTwo.set) {
for (let name in calcFunc) {
if (mathType.type === name) {
miniView.innerHTML = calcFunc[name](mathHoldOne.num, mathHoldTwo.num);
mathHoldOne.num = calcFunc[name](mathHoldOne.num, mathHoldTwo.num);
}
}
;
mathHoldTwo.num = 0;
mathHoldTwo.set = false;
mathType.type = 'subtract';
}
break;
case('cell equal'):
mathHoldTwo.num = parseInt(screenValue.innerHTML);
if (mathType.type === "add") {
screenValue.innerHTML = calcFunc.add(mathHoldOne.num, mathHoldTwo.num);
miniView.innerHTML = calcFunc.add(mathHoldOne.num, mathHoldTwo.num);
mathHoldTwo.num = 0;
mathHoldOne.num = 0;
mathHoldOne.set = false;
} else if (mathType.type === "subract") {
screenValue.innerHTML = calcFunc.subtract(mathHoldOne.num, mathHoldTwo.num);
miniView.innerHTML = calcFunc.subtract(mathHoldOne.num, mathHoldTwo.num);
mathHoldOne.num = (mathHoldOne.num - mathHoldTwo.num);
mathHoldTwo.num = 0;
mathHoldOne.num = 0;
mathHoldOne.set = false;
}
else if (mathType.type === "mulitply") {
screenValue.innerHTML = calcFunc.multiply(mathHoldOne.num, mathHoldTwo.num);
miniView.innerHTML = calcFunc.multiply(mathHoldOne.num, mathHoldTwo.num);
mathHoldOne.num = (mathHoldOne.num * mathHoldTwo.num);
mathHoldTwo.num = 0;
mathHoldOne.num = 0;
mathHoldOne.set = false;
} else if (mathType.type === "divide") {
screenValue.innerHTML = calcFunc.divide(mathHoldOne.num, mathHoldTwo.num);
miniView.innerHTML = calcFunc.divide(mathHoldOne.num, mathHoldTwo.num);
mathHoldOne.num = (mathHoldOne.num / mathHoldTwo.num);
mathHoldTwo.num = 0;
mathHoldOne.num = 0;
mathHoldOne.set = false;
}
break;
}
console.log(mathHoldOne, mathHoldTwo, mathType.type);
})
}
};
view.updateView();
view.btnHandle();
const calcFunc = {
add: function (x, y) {
return x + y;
},
subtract: function (x, y) {
return x - y;
},
multiply: function (x, y) {
return x * y;
},
divide: function (x, y) {
return x / y;
},
clear: function () {
let view = document.querySelector('js-view');
view.innerHTML = '';
}
}
</code></pre>
| 3 | 5,570 |
Popup in style of ContentControl not updating
|
<p>I have a ContentControl with a style that contains a popup that wraps a textbox. I know it sounds a little confusing but I will post some code below. When the caps lock key is on the popup is shown, but when the window is dragged the popup does not move with it. </p>
<p>I need to figure out how to update the location of the popup in they style. </p>
<p>This ContentControl is used on both a window and UserControl so that is why I am trying to address this in the style.</p>
<p>This question differs from some of the others as I am trying to solve it in the style and not code.</p>
<p>The content control:</p>
<pre><code>public class ShowCapLockWarningControler : ContentControl
{
static ShowCapLockWarningControler()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ShowCapLockWarningControler), new FrameworkPropertyMetadata(typeof(ShowCapLockWarningControler)));
}
public static readonly DependencyProperty ShowMessageProperty =
DependencyProperty.Register(Reflection.GetPropertyName<ShowCapLockWarningControler>(i => i.ShowMessage), typeof(bool),
typeof(ShowCapLockWarningControler), new PropertyMetadata(false));
public bool ShowMessage
{
get { return (bool)GetValue(ShowMessageProperty); }
set { SetValue(ShowMessageProperty, value); }
}
public ShowCapLockWarningControler()
{
IsKeyboardFocusWithinChanged += (s, e) => RecomputeShowMessage();
PreviewKeyDown += (s, e) => RecomputeShowMessage();
PreviewKeyUp += (s, e) => RecomputeShowMessage();
}
private void RecomputeShowMessage()
{
ShowMessage = IsKeyboardFocusWithin && Console.CapsLock;
}
}
</code></pre>
<p>How its used:</p>
<pre><code><controls:ShowCapLockWarningControler Grid.Row="1" Grid.Column="2" Style="{DynamicResource CaplockWarning}">
<PasswordBox Width="150" Name="PasswordBox" PasswordChanged="HandlePasswordChanged" VerticalContentAlignment="Center"
KeyDown="HandlePasswordBoxEnterPressed"/>
</controls:ShowCapLockWarningControler>
</code></pre>
<p>The style in the style dictionary:</p>
<pre><code><Style x:Key="CaplockWarning" TargetType="{x:Type controls:ShowCapLockWarningControler}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:ShowCapLockWarningControler}">
<Grid>
<ContentPresenter Name="Presenter"/>
<Popup Placement="Bottom" PlacementTarget="{Binding ElementName=Presenter}" Name="BalloonPopup" AllowsTransparency="True"
IsOpen="{TemplateBinding ShowMessage}" >
<!-- Visual of the popup-->
</Popup>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
| 3 | 1,214 |
Java Applet Grid Game Flashing On Refresh/Keypress
|
<p>I made a simple game on a grid in java that involves controlling a white square with the WASD keys. Whenever I press W,S,A, or D, the screen sometimes flickers before drawing the grid again. I am fairly new to coding, so the more you can dumb it down for me, the better.</p>
<pre><code>import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/**
* DotGame.applet
*
* A simple game where the player controls a white circle with the WASD keys.
* - If the user moves his circle over a green circle, his score will go up by 1, and another red circle will spawn.
* - If the user moves his circle over a red circle, his score will go down by 1, and one less red circle will be generated.
* - There is no win condition, it is just a test game.
*
* @author -----------
* @version 11-9-2014
*/
public class DotGame extends Applet
implements KeyListener, MouseListener
{
int width,height;
int powerup = 1;
int click = 0;
int x,y;
final int size = 40;
int ox = size,oy = size;
int rx = 0, ry = 0;
int reddots = 0;
int red[][] = new int[1000][2];
String s = "";
int score = 0;
int DrawGrid = 0;
String sc = "";
int powerupdots = 1;
int yellow[][] = new int[1][2];
int powerupcounter = 0;
int shield = 0;
int blue[][] = new int[1][2];
public void init()
{
this.setSize(740,500);
width = 640;
height = 480;
setBackground( Color.black );
x = width/2;
y = height/2;
s = "CLICK TO START";
addMouseListener( this );
addKeyListener( this );
}
public void keyPressed( KeyEvent e ) { }
public void keyReleased ( KeyEvent e ) { }
public void keyTyped( KeyEvent e )
{
char c = e.getKeyChar();
String t = c+"";
//This will change the coordinates of the user-controlled circle by the size of the circle based on what button is pressed
if(powerupcounter > 0)
{
powerup = 2;
}
else if(powerupcounter == 0)
{
powerup = 1;
}
if( t.equalsIgnoreCase("w" )&& oy > 0+((powerup-1)*size))
{
oy = oy-(size*powerup);
}
else if( t.equalsIgnoreCase("s") && oy < height-(size*powerup))
{
oy = oy+(size*powerup);
}
else if( t.equalsIgnoreCase("a")&& ox > 0+((powerup-1)*size))
{
ox = ox-(size*powerup);
}
else if( t.equalsIgnoreCase("d") && ox < width-(size*powerup))
{
ox = ox+(size*powerup);
}
else if(t.equalsIgnoreCase("w" ) && oy == 0)
{
oy = height-(size*powerup);
}
else if(t.equalsIgnoreCase("s") && oy == height-size)
{
oy = 0+((powerup-1)*size);
}
else if(t.equalsIgnoreCase("a") && ox == 0)
{
ox = width-(size*powerup);
}
else if(t.equalsIgnoreCase("d") && ox == width-size)
{
ox = 0+((powerup-1)*size);
}
else if(t.equalsIgnoreCase("w") && oy == size && powerup ==2)
{
oy = height-size;
}
else if(t.equalsIgnoreCase("s") && oy == height -(size*powerup) && powerup ==2)
{
oy = 0;
}
else if(t.equalsIgnoreCase("a") && ox == size && powerup ==2)
{
ox = width-size;
}
else if(t.equalsIgnoreCase("d") && ox == width -(size*powerup) && powerup ==2)
{
ox = 0;
}
if(powerupcounter > 0)
{
powerupcounter--;
}
repaint();
e.consume();
}
public void mouseEntered( MouseEvent e) {}
public void mouseExited( MouseEvent e) {}
public void mousePressed( MouseEvent e) {}
public void mouseReleased( MouseEvent e) {}
public void mouseClicked( MouseEvent e)
{
if(click == 0)
{
randomYellow();
randomBlue();
DrawRandom();
x = e.getX();
y = e.getY();
s = "";
repaint();
e.consume();
click = 1;
}
}
public void CheckScore()
{
if(ox == rx && oy == ry)
{
score++;
reddots+=10;
DrawRandom();
}
}
public void DrawRandom()
{
//The reason we divide by the size and then multiply after it is an int is to
//make sure that the random circle drawn is in the same base as the size of the circle,
//so that the player's circle can move directly over it, and not be of by a fraction
//of the predetermined size.
rx = (int)(Math.random()*width/size)*size;
ry = (int)(Math.random()*height/size)*size;
while(rx == ox && ry == oy)
{
rx = (int)(Math.random()*width/size)*size;
ry = (int)(Math.random()*height/size)*size;
}
for(int y = 0 ; y < reddots ; y++)
{
red[y][0] = (int)(Math.random()*width/size)*size;
red[y][1] = (int)(Math.random()*height/size)*size;
while(red[y][0] == rx && red[y][1] == ry || red[y][0] == yellow[0][0] && red[y][1] == yellow[0][1]
|| red[y][0] == ox && red[y][1] == oy || red[y][0] == blue[0][0] && red[y][1] == blue[0][1])
{
red[y][0] = (int)(Math.random()*width/size)*size;
red[y][1] = (int)(Math.random()*height/size)*size;
}
}
}
public void randomYellow()
{
yellow[0][0] = (int)(Math.random()*width/size)*size;
yellow[0][1] = (int)(Math.random()*height/size)*size;
while(yellow[0][0] == rx && yellow[0][1] == ry)
{
yellow[0][0] = (int)(Math.random()*width/size)*size;
yellow[0][1] = (int)(Math.random()*height/size)*size;
}
}
public void randomBlue()
{
blue[0][0] = (int)(Math.random()*width/size)*size;
blue[0][1] = (int)(Math.random()*height/size)*size;
while(blue[0][0] == rx && blue[0][1] == ry || blue[0][0] == yellow[0][0] && blue[0][1] == yellow[0][1])
{
blue[0][0] = (int)(Math.random()*width/size)*size;
blue[0][1] = (int)(Math.random()*height/size)*size;
}
}
public void CheckDeath()
{
for(int y = 0 ; y < reddots ; y++)
{
if(ox == red[y][0] && oy == red[y][1] && shield == 0)
{
score--;
reddots--;
DrawRandom();
}
else if(ox == red[y][0] && oy == red[y][1] && shield !=0)
{
shield--;
DrawRandom();
}
}
}
public void CheckPowerup()
{
for(int y = 0 ; y < powerupdots ; y++)
{
if(ox == yellow[y][0] && oy == yellow[y][1])
{
powerupcounter += 10;
randomYellow();
}
}
}
public void CheckShield()
{
if(ox == blue[0][0] && oy == blue[0][1] && shield < 5)
{
shield++;
randomBlue();
}
else if(ox == blue[0][0] && oy == blue[0][1] && shield >= 5)
{
randomBlue();
}
}
public void CheckWin( Graphics g )
{
g.setColor(Color.black);
g.fillRect(0,0,width,height);
while(1 == 1)
{
g.drawString( "YOU WIN" , width/2, height/2);
}
}
public void paint( Graphics g )
{
CheckScore();
if(score == 20)
{
CheckWin(g);
}
CheckDeath();
CheckPowerup();
CheckShield();
DrawGrid(g);
g.setColor(Color.yellow);
g.fillRect(yellow[0][0],yellow[0][1],size+1,size+1);
g.setColor(Color.red);
for(int y = 0; y < reddots ; y++)
{
g.fillRect(red[y][0],red[y][1],size+1,size+1);
}
sc = ""+score;
//Draw user
g.setColor(Color.white);
g.fillRect(ox,oy,size+1,size+1);
//Draw shield around user if they have shields (max 5)
if(shield >= 1)
{
g.setColor(Color.blue);
g.fillRect(ox,oy,size+1,5);
g.fillRect(ox,oy,5,size+1);
g.fillRect(ox,oy+size-4,size+1,5);
g.fillRect(ox+size-4,oy,5,size+1);
}
//Draw green tile
g.setColor(Color.green);
g.fillRect(rx,ry,size+1,size+1);
//Draw shield tile
g.setColor(Color.blue);
g.fillRect(blue[0][0],blue[0][1],size+1,size+1);
g.setColor( Color.green );
g.drawString( s, x, y );
g.drawString( "Score : "+sc, 650, 20);
g.drawString( "Powerups : "+powerupcounter, 650, 40);
g.drawString( "Red Dots : "+reddots, 650,60);
g.drawString( "Shield : "+shield,650,80);
}
public void DrawGrid( Graphics g )
{
g.setColor(Color.orange);
for(int x = 0 ; x <= width ; x += size)
{
g.drawLine(x,0,x,height);
}
for(int y = 0 ; y <= height ; y+= size)
{
g.drawLine(0,y,width,y);
}
}
</code></pre>
<p>}</p>
| 3 | 4,016 |
rails : gmaps4rails gem not showing sidebar after deployment
|
<p>I have a really tiny problem that is a huge feature for the site.
Just a quick overview I developed the rails app in development mode and used the gmaps4rails app which worked fine. However I deployed the app to Heroku and now the gmaps4rails does not show the sidebar.</p>
<p>Below is an image of how it should look like:
<a href="http://i.stack.imgur.com/UJQ1X.png" rel="nofollow">image</a>
So when the user clicks on any of the sidebar entries it takes the user to the correct marker on the map.</p>
<p>Below is an image of how it is rendered in production/Heroku
<a href="http://i.stack.imgur.com/vlNzU.png" rel="nofollow">image</a>
As you can see there is no sidebar entries.</p>
<p>Upon looking at the source code which is rendered there is one difference.
In the development mode this line of code is present <code>Gmaps.map.markers_conf.list_container = "ranchlist";</code> This code is the code that gets the list and displays it.</p>
<p>Below is the code for the view itself:</p>
<pre><code><div id="mapscontainer">
<%= gmaps("markers" => {"data" => @json, "options" => {"list_container" => "ranchlist"}},
:map_options => {"auto_adjust" => true, "zoom" => 17,
:raw => '{
panControl: true,
zoomControl: true,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false,
scrollwheel: false,
zoom: 20,
}'
},
:markers => { :data => @json }
)%>
<div id="ranchcontainer">
<ul id="ranchlist"><h2>Find A Mash's Wing Ranch <span style="font-size:25px;"><sup>&reg;</sup></span></h2>
<h1>Near You</h1></br>
<%= image_tag("locations/locations_line.png", :class => "lineseperator") %>
</ul>
</div>
</div>
</code></pre>
| 3 | 1,111 |
Why does this node.js app runs locally by Heroku however is not loading in Heroku?
|
<p>I'm trying to deploy an app for the first time using Heroku, after successfully committing the repo and pushing to the changes to Heroku, the app still doesn't load.</p>
<p>Heroku Logs: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>2020 - 03 - 04 T11: 06: 06.898178 + 00: 00 heroku[web .1]: State changed from starting to crashed
2020 - 03 - 04 T11: 06: 06.806047 + 00: 00 app[web .1]: npm ERR!missing script: start
2020 - 03 - 04 T11: 06: 06.820983 + 00: 00 app[web .1]:
2020 - 03 - 04 T11: 06: 06.821278 + 00: 00 app[web .1]: npm ERR!A complete log of this run can be found in:
2020 - 03 - 04 T11: 06: 06.821337 + 00: 00 app[web .1]: npm ERR!/app/.npm / _logs / 2020 - 03 - 04 T11_06_06_806Z - debug.log
2020 - 03 - 04 T11: 06: 06.881460 + 00: 00 heroku[web .1]: Process exited with status 1
2020 - 03 - 04 T11: 09: 27.000000 + 00: 00 app[api]: Build started by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 09: 40.461743 + 00: 00 app[api]: Deploy b856e1a0 by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 09: 40.461743 + 00: 00 app[api]: Release v11 created by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 09: 40.921846 + 00: 00 heroku[web .1]: State changed from crashed to starting
2020 - 03 - 04 T11: 09: 40.000000 + 00: 00 app[api]: Build succeeded
2020 - 03 - 04 T11: 09: 43.094952 + 00: 00 heroku[web .1]: Starting process with command `npm start`
2020 - 03 - 04 T11: 09: 45.156685 + 00: 00 heroku[web .1]: State changed from starting to crashed
2020 - 03 - 04 T11: 09: 45.097670 + 00: 00 app[web .1]: npm ERR!missing script: start
2020 - 03 - 04 T11: 09: 45.102936 + 00: 00 app[web .1]:
2020 - 03 - 04 T11: 09: 45.103180 + 00: 00 app[web .1]: npm ERR!A complete log of this run can be found in:
2020 - 03 - 04 T11: 09: 45.103338 + 00: 00 app[web .1]: npm ERR!/app/.npm / _logs / 2020 - 03 - 04 T11_09_45_098Z - debug.log
2020 - 03 - 04 T11: 09: 45.139795 + 00: 00 heroku[web .1]: Process exited with status 1
2020 - 03 - 04 T11: 11: 52.000000 + 00: 00 app[api]: Build started by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 12: 05.304994 + 00: 00 heroku[web .1]: State changed from crashed to starting
2020 - 03 - 04 T11: 12: 05.046524 + 00: 00 app[api]: Deploy 44 da3cc6 by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 12: 05.046524 + 00: 00 app[api]: Release v12 created by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 12: 07.607259 + 00: 00 heroku[web .1]: Starting process with command `npm start`
2020 - 03 - 04 T11: 12: 05.000000 + 00: 00 app[api]: Build succeeded
2020 - 03 - 04 T11: 12: 09.990662 + 00: 00 heroku[web .1]: State changed from starting to up
2020 - 03 - 04 T11: 12: 09.637412 + 00: 00 app[web .1]:
2020 - 03 - 04 T11: 12: 09.637434 + 00: 00 app[web .1]: > airbnb @1 .0 .0 start / app
2020 - 03 - 04 T11: 12: 09.637434 + 00: 00 app[web .1]: > node index.js
2020 - 03 - 04 T11: 12: 09.637435 + 00: 00 app[web .1]:
2020 - 03 - 04 T11: 12: 09.804031 + 00: 00 app[web .1]: server is running
2020 - 03 - 04 T11: 14: 33.000000 + 00: 00 app[api]: Build started by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 14: 46.829363 + 00: 00 heroku[web .1]: Restarting
2020 - 03 - 04 T11: 14: 46.832814 + 00: 00 heroku[web .1]: State changed from up to starting
2020 - 03 - 04 T11: 14: 46.617874 + 00: 00 app[api]: Deploy ebc34190 by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 14: 46.617874 + 00: 00 app[api]: Release v13 created by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 14: 47.000000 + 00: 00 app[api]: Build succeeded
2020 - 03 - 04 T11: 14: 47.874543 + 00: 00 heroku[web .1]: Stopping all processes with SIGTERM
2020 - 03 - 04 T11: 14: 47.977184 + 00: 00 heroku[web .1]: Process exited with status 143
2020 - 03 - 04 T11: 14: 49.232441 + 00: 00 heroku[web .1]: Starting process with command `node index.js`
2020 - 03 - 04 T11: 14: 51.656608 + 00: 00 heroku[web .1]: State changed from starting to up
2020 - 03 - 04 T11: 14: 51.560969 + 00: 00 app[web .1]: server is running
2020 - 03 - 04 T11: 20: 46.000000 + 00: 00 app[api]: Build started by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 20: 59.379726 + 00: 00 app[api]: Deploy b253d4d4 by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 20: 59.379726 + 00: 00 app[api]: Release v14 created by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 21: 00.304391 + 00: 00 heroku[web .1]: Restarting
2020 - 03 - 04 T11: 21: 00.308413 + 00: 00 heroku[web .1]: State changed from up to starting
2020 - 03 - 04 T11: 20: 59.000000 + 00: 00 app[api]: Build succeeded
2020 - 03 - 04 T11: 21: 01.360046 + 00: 00 heroku[web .1]: Stopping all processes with SIGTERM
2020 - 03 - 04 T11: 21: 01.466415 + 00: 00 heroku[web .1]: Process exited with status 143
2020 - 03 - 04 T11: 21: 03.924313 + 00: 00 heroku[web .1]: Starting process with command `node index.js`
2020 - 03 - 04 T11: 21: 06.294179 + 00: 00 app[web .1]: server is running
2020 - 03 - 04 T11: 21: 07.763819 + 00: 00 heroku[web .1]: State changed from starting to up
2020 - 03 - 04 T11: 30: 52.000000 + 00: 00 app[api]: Build started by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 31: 06.009751 + 00: 00 heroku[web .1]: Restarting
2020 - 03 - 04 T11: 31: 06.013344 + 00: 00 heroku[web .1]: State changed from up to starting
2020 - 03 - 04 T11: 31: 05.790725 + 00: 00 app[api]: Deploy bd9bf403 by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 31: 05.790725 + 00: 00 app[api]: Release v15 created by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 31: 07.206890 + 00: 00 heroku[web .1]: Stopping all processes with SIGTERM
2020 - 03 - 04 T11: 31: 07.283478 + 00: 00 heroku[web .1]: Process exited with status 143
2020 - 03 - 04 T11: 31: 06.000000 + 00: 00 app[api]: Build succeeded
2020 - 03 - 04 T11: 31: 07.922427 + 00: 00 heroku[web .1]: Starting process with command `npm start`
2020 - 03 - 04 T11: 31: 09.697432 + 00: 00 app[web .1]:
2020 - 03 - 04 T11: 31: 09.697448 + 00: 00 app[web .1]: > airbnb @1 .0 .0 start / app
2020 - 03 - 04 T11: 31: 09.697449 + 00: 00 app[web .1]: > node index.js
2020 - 03 - 04 T11: 31: 09.697449 + 00: 00 app[web .1]:
2020 - 03 - 04 T11: 31: 09.841347 + 00: 00 app[web .1]: server is running
2020 - 03 - 04 T11: 31: 10.158006 + 00: 00 heroku[web .1]: State changed from starting to up
2020 - 03 - 04 T11: 39: 27.000000 + 00: 00 app[api]: Build started by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 39: 40.313098 + 00: 00 app[api]: Deploy 5 d445be2 by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 39: 40.313098 + 00: 00 app[api]: Release v16 created by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 39: 40.000000 + 00: 00 app[api]: Build succeeded
2020 - 03 - 04 T11: 39: 41.143634 + 00: 00 heroku[web .1]: Restarting
2020 - 03 - 04 T11: 39: 41.161325 + 00: 00 heroku[web .1]: State changed from up to starting
2020 - 03 - 04 T11: 39: 41.887182 + 00: 00 heroku[web .1]: Stopping all processes with SIGTERM
2020 - 03 - 04 T11: 39: 41.956999 + 00: 00 heroku[web .1]: Process exited with status 143
2020 - 03 - 04 T11: 39: 43.484238 + 00: 00 heroku[web .1]: Starting process with command `node index.js`
2020 - 03 - 04 T11: 39: 45.834243 + 00: 00 app[web .1]: server is running
2020 - 03 - 04 T11: 39: 46.339851 + 00: 00 heroku[web .1]: State changed from starting to up
2020 - 03 - 04 T11: 41: 00.000000 + 00: 00 app[api]: Build started by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 41: 13.457898 + 00: 00 heroku[web .1]: Restarting
2020 - 03 - 04 T11: 41: 13.473960 + 00: 00 heroku[web .1]: State changed from up to starting
2020 - 03 - 04 T11: 41: 12.858989 + 00: 00 app[api]: Deploy 7357470 a by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 41: 12.858989 + 00: 00 app[api]: Release v17 created by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 41: 13.000000 + 00: 00 app[api]: Build succeeded
2020 - 03 - 04 T11: 41: 14.845852 + 00: 00 heroku[web .1]: Stopping all processes with SIGTERM
2020 - 03 - 04 T11: 41: 14.948458 + 00: 00 heroku[web .1]: Process exited with status 143
2020 - 03 - 04 T11: 41: 17.987602 + 00: 00 heroku[web .1]: Starting process with command `node index.js`
2020 - 03 - 04 T11: 41: 21.528516 + 00: 00 app[web .1]: server is running
2020 - 03 - 04 T11: 41: 22.657768 + 00: 00 heroku[web .1]: State changed from starting to up
2020 - 03 - 04 T11: 48: 56.000000 + 00: 00 app[api]: Build started by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 49: 10.202399 + 00: 00 heroku[web .1]: Restarting
2020 - 03 - 04 T11: 49: 10.205603 + 00: 00 heroku[web .1]: State changed from up to starting
2020 - 03 - 04 T11: 49: 09.824296 + 00: 00 app[api]: Deploy 9 dbe0b02 by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 49: 09.824296 + 00: 00 app[api]: Release v18 created by user freecorpteam @gmail.com
2020 - 03 - 04 T11: 49: 10.000000 + 00: 00 app[api]: Build succeeded
2020 - 03 - 04 T11: 49: 11.335018 + 00: 00 heroku[web .1]: Stopping all processes with SIGTERM
2020 - 03 - 04 T11: 49: 11.464510 + 00: 00 heroku[web .1]: Process exited with status 143
2020 - 03 - 04 T11: 49: 11.944025 + 00: 00 heroku[web .1]: Starting process with command `node index.js`
2020 - 03 - 04 T11: 49: 13.650108 + 00: 00 heroku[web .1]: State changed from starting to up
2020 - 03 - 04 T11: 49: 13.488186 + 00: 00 app[web .1]: server is running</code></pre>
</div>
</div>
</p>
<p><strong>index.js</strong> </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const bodyParser = require('body-parser'),
express = require('express'),
app = express();
// Setting up the app
app.use(express.static('public'));
app.set('view engine', 'ejs');
// ================= Display routes ==================
// === Root route ===
app.get('/', function(req, res) {
res.render('home');
});
app.get('/blog', function(req, res) {
res.render('blog');
});
app.listen(process.env.PORT, function() {
console.log('server is running');
});</code></pre>
</div>
</div>
</p>
<p><strong>package.json</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
"name": "airbnb",
"version": "1.0.0",
"description": "Airbnb guide",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "Freedom Corporation",
"license": "ISC",
"dependencies": {
"ejs": "^3.0.1",
"express": "^4.17.1"
}
}</code></pre>
</div>
</div>
</p>
<p><strong>Procfile</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>web: node index.js</code></pre>
</div>
</div>
</p>
<p>The app runs fine locally, I've tried to add multiple times the start script and also re initialized npm several times. </p>
<p>Thanks, </p>
| 3 | 4,168 |
Adding transition to CSS
|
<p>I want to add smooth animated transition to drop down in this CSS. Which code and where I should place? I have tried some "webkit-transition" variants but none worked with my skills in programming. Anyone can solve this problem?</p>
<pre><code> ul.jb_free_dropdown,
ul.jb_free_dropdown li,
ul.jb_free_dropdown ul {
list-style: none;
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
}
ul.jb_free_dropdown {
position: relative;
z-index: 597;
float: left;
}
ul.jb_free_dropdown li {
float: left;
min-height: 1px;
line-height: 1.3em;
vertical-align: middle;
}
ul.jb_free_dropdown li.hover,
ul.jb_free_dropdown li:hover {
position: relative;
z-index: 599;
cursor: default;
}
ul.jb_free_dropdown ul {
visibility: hidden;
position: absolute;
top: 100%;
left: 0;
z-index: 598;
width: 100%;
}
ul.jb_free_dropdown ul li {
float: none;
}
ul.jb_free_dropdown ul ul {
top: 0px;
left: 100%;
}
ul.jb_free_dropdown li:hover > ul {
visibility: visible;
}
/* -- Base drop-down styling -- */
ul.jb_free_dropdown {
font-weight: bold;
}
ul.jb_free_dropdown li {
padding: 7px 10px;
border-style: solid;
border-width: 1px 1px 1px 0;
border-color: #fff #d9d9d9 #d9d9d9;
background-color: #f6f6f6;
color: #000;
}
ul.jb_free_dropdown li.hover,
ul.jb_free_dropdown li:hover,
ul.jb_free_dropdown li.on {
background-color: #eee;
color: #000;
}
ul.jb_free_dropdown a:link,
ul.jb_free_dropdown a:visited { color: #000; text-decoration: none; }
ul.jb_free_dropdown a:hover { color: #000; background-color: #ececec;}
ul.jb_free_dropdown a:active { color: #000; }
/* -- level mark -- */
ul.jb_free_dropdown ul {
width: 200px;
margin-top: 1px;
}
ul.jb_free_dropdown ul li {
font-weight: normal;
}
ul.jb_free_dropdown a,
ul.jb_free_dropdown span {
display: block;
padding: 10px 20px;
background-color: #ffffff;
background-repeat: repeat-x;
}
/* -- Base style override -- */
ul.jb_free_dropdown li {
padding: 0;
border: none;
}
/*
JB
*/
ul.jb_free_dropdown li li.parent a {
background: #f4f4f4 url('../../media/images/arrow.png') right 10px no-repeat;
}
ul.jb_free_dropdown li li.parent li a {
background: #f4f4f4;
}
ul.jb_free_dropdown li.parent a:hover {
background-color: #ececec;
}
ul.jb_free_dropdown li.active a {
background-color: #fff;
}
ul.jb_free_dropdown li.active li a {
background-color: #f4f4f4;
}
ul.jb_free_dropdown li.active li a:hover {
background-color: #ececec;
}
/*
JB
*/
ul.jb_free_dropdown ul a,
ul.jb_free_dropdown ul span {
padding: 8px;
}
/* -- Base style reinitiate: post-override activities -- */
/* -- Custom styles -- */
ul.jb_free_dropdown li.hover,
ul.jb_free_dropdown li:hover {
background: url(../../../../images/default/grad2.png) 0 100% repeat-x;
color: #000;
background-color: #fff;
}
ul.jb_free_dropdown li:hover {
color: #fff;
}
ul.jb_free_dropdown li a:active {
background: url(../../../../images/default/grad1.png) repeat-x;
}
ul.jb_free_dropdown ul {
margin-top: 0;
}
/* -- Mixed -- */
ul.jb_free_dropdown li a,
ul.jb_free_dropdown *.dir {
border-style: solid;
border-width: 1px 1px 1px 0;
border-color: #fff #d9d9d9 #d9d9d9;
}
/* -- Drop-down open -- */
</code></pre>
| 3 | 1,957 |
scrape multiple clubs per player in one cell of the java script table - display both in the same list element
|
<p>My problem is, that in the last cell of the javascript table, I get the clubs the player played for via the "img".</p>
<pre><code>injury_list = []
season_list = []
day_list = []
missedgame_list = []
team_list = []
player_list = []
</code></pre>
<pre><code> url = 'https://www.transfermarkt.ch/emre-can/verletzungen/spieler/119296/ajax/yw1/page1'
response = requests.get(url, headers={'User-Agent': 'Custom5'})
injury_data = response.text
soup = BeautifulSoup(injury_data, 'html.parser')
table = soup.find(id="yw1")
injurytypes = table.select("td[class='hauptlink bg_rot_20']") + table.select("td[class='hauptlink']")
all_injuries = [injury.text for injury in injurytypes]
injury_list.extend(all_injuries)
seasons = table.select("td[class='zentriert bg_rot_20']") + table.select("td[class='zentriert']")
all_seasons = [season.text for season in seasons]
season_list.extend(all_seasons)
days = table.select("td[class='rechts bg_rot_20']") + table.select("td[class='rechts']")
all_days =[float(day.text.split()[0]) for day in days]
day_list.extend(all_days)
missedgames = table.select("td[class='rechts hauptlink wappen_verletzung bg_rot_20']") + table.select("td[class='rechts hauptlink wappen_verletzung']")
all_missedgames = [float(missedgame.text.replace("-", "0")) for missedgame in missedgames]
missedgame_list.extend(all_missedgames)
for item in table.select('img', class_='tiny_wappen', recursive=True):
team_list.append(item.get('alt'))
</code></pre>
<p>i need a dataframe with the different cell entries and that when there are two clubs, I have both clubs in the same dataframe cell Juventus Turin / Borussia Dortmund.
Otherwise I have a problem, that the code returns lists from different lenght, respectively not everything fits togehter in a dataframe.</p>
<p>I already tried it with if loops to indicate that if there are two img in one cell etc. but did not succeed.</p>
<p>Thank you very much.</p>
<pre><code>season_list_def = season_list[0::3]
startdate_list = season_list[1::3]
enddate_list = season_list[2::3]
</code></pre>
<pre><code>df = pd.DataFrame({"injurytype": injury_list, "season": season_list_def, "injury_start": startdate_list, "injury_end": enddate_list, "absence_duration": day_list, "missed_games": missedgame_list, "Team": np.nan})
df.loc[df["missed_games"] != 0, "Team"] = team_list #this is not working because the lenght of team list is not from equal size because I have two clubs in one cell.
df
</code></pre>
| 3 | 1,121 |
how to resolve the problem that hovering mouse on chart will appear old data/charts?
|
<p>I used react hooks useEffect for rendering a chart from chart.js to canvas. However, I found problem of old chart showing when I hover my mouse on the chart. From the sources I found online I realized the problem might be able to solve by chart.destroy(), but I just do not know where and how to use it in my case of code. I have attached a snip of my code here, hope anybody can help me out.</p>
<pre><code>import React, { useEffect } from 'react';
import Chart from 'chart.js';
import { Card } from 'components/Card';
import { localDateTime, dateFilter } from 'helpers';
const red = '#644DFF';
const purple = '#F73F64';
const DailyTrafficCard = (props) => {
const { store, capacity, data, setVar} = props;
const lastSevenDays = Array(7)
.fill()
.map((_, i) => {
const localdate = localDateTime(store);
return localdate()
.subtract(i, 'day')
.format('YYYY-MM-DD[T]07:00:00[Z]');
});
useEffect(() => {
const ctx = document && document.querySelector('#daily-traffic-chart');
if (!ctx) {
return;
}
const bar = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: data[data.length-1],
barThickness: 13,
backgroundColor: (ctx) => {
const idx = ctx && ctx.dataIndex;
const val = ctx && ctx.dataset && ctx.dataset.data && ctx.dataset.data[idx];
return val < 40 ? purple : red;
}
}]
},
options: {
intersect: false,
legend: {
display: false,
},
scales: {
xAxes: [{
type: 'time',
offset: true,
time: {
unit: 'hour',
displayFormats: {
hour: 'HH',
},
},
ticks: {},
gridLines: {
display: false,
},
}],
yAxes: [{
gridLines: {
display: true,
},
ticks: {
beginAtZero: true,
min: 0,
max: capacity,
stepSize: 5
},
}],
},
}
});
}, [data,capacity]);
const handleOnChange = (event) => {
setVar(event.target.value);
}
return (
<Card
classname="DailyTrafficCard"
icon={<span><i className="icon-user"/></span>}
title={<h3>Daily Traffic Analytics</h3>}>
<div className="daily">
<div className="daily-head p-4 text-center">
<select className="py-2 px-3" onChange={handleOnChange}>
{lastSevenDays.map(date => (
<option key={date} value={date}>{dateFilter(date, 'dddd')}</option>
))}
</select>
</div>
<div className="px-8">
{data && data.length > 0 && (
<canvas width="250" id="daily-traffic-chart"></canvas>
)}
</div>
</div>
</Card>
)
}
export {
DailyTrafficCard
}
</code></pre>
| 3 | 1,712 |
How to add several fields in a module that belong to two tables in the same form or other - Prestashop 1.7
|
<p>I have followed the steps of a tutorial to create a module to edit invoices specifically this:
<a href="https://blog.floriancourgey.com/2018/04/edit-your-invoices-in-prestashop" rel="nofollow noreferrer">https://blog.floriancourgey.com/2018/04/edit-your-invoices-in-prestashop</a></p>
<p>But the module only allows updating the information of the fields that appear in a single table.</p>
<p>The thing is, I need to add a new field that belongs to another table and is saved in both tables.
The table that stores the module information is ps_order_invoice and the table that I also want to save, a single invoice_number field, is ps_orders.</p>
<pre><code> class AdminCustomInvoicesController extends ModuleAdminController {
public function __construct(){
parent::__construct();
$this->bootstrap = true; // use Bootstrap CSS
$this->table = 'order_invoice'; // SQL table name, will be prefixed with _DB_PREFIX_
$this->identifier = 'id_order_invoice'; // SQL column to be used as primary key
$this->className = 'OrderInvoice'; // PHP class name
$this->allow_export = true; // allow export in CSV, XLS..
$this->_orderBy = 'date_add'; // default SQL ORDER BY
$this->page_header_toolbar_title = 'Invoices'; // toolbar title
$this->_select = 'concat(upper(c.lastname), " ", c.firstname) as customer';
$this->_join = '
JOIN '._DB_PREFIX_.'orders o ON (o.id_order = a.id_orderes)
JOIN '._DB_PREFIX_.'customer c ON (c.id_customer = o.id_customer)
';
$this->fields_list = [
'id_order_invoice' => ['title' => $this->trans('ID', [], 'Admin.Global'),'class' => 'fixed-width-xs'],
'number' => ['title' => $this->trans('Number', [], 'Admin.Global'),'class' => 'fixed-width-xs'],
//I want add this new field(invoice_number) in another table ps_orders
'invoice_number' => ['title' => $this->trans('Invoice Number', [], 'Admin.Global'),'class' => 'fixed-width-xs'],
'date_add' => ['title' => $this->trans('Date', [], 'Admin.Global'), 'type'=>'datetime'],
'customer' => ['title' => $this->trans('Customer', [], 'Admin.Global')],
'total_products_wt' => ['title' => $this->trans('Total products', [], 'Admin.Global'),
'align' => 'text-right',
'type' => 'price',
],
'total_shipping_tax_incl' => ['title' => $this->trans('Total shipping', [], 'Admin.Global'),
'align' => 'text-right',
'type' => 'price',
],
'total_paid_tax_incl' => ['title' => $this->trans('Total paid', [], 'Admin.Global'),
'align' => 'text-right',
'type' => 'price',
],
];
</code></pre>
<p>I have also added in field_list</p>
<pre><code>$this->fields_form = [
'legend' => ['title' => $this->l('Custom Invoice'),'icon' => 'icon-list-ul'],
'input' => [
['name' => 'date_add','type' => 'datetime','label' => 'Date add',],
['name'=>'number','type'=>'text','required' => true,'label' => 'Number',],
//Here I add new field from ps_orders
['name'=>'invoice_number','type'=>'text','required' => true,'label' => 'Invoice number',],
['name'=>'note','type'=>'textarea','label' => 'Note',],
['name'=>'delivery_number','type'=>'text','label'=>'Delivery number'],
['name'=>'delivery_date','type'=>'datetime','label'=>'Delivery date'],
['name'=>'total_discount_tax_excl','type'=>'text','label'=>'Total amount of discounts (no tax)'],
['name'=>'total_discount_tax_incl','type'=>'text','label'=>'Total amount of discounts (with tax)'],
['name'=>'total_shipping_tax_excl','type'=>'text','label'=>'Total cost of shipping (no tax)'],
['name'=>'total_shipping_tax_incl','type'=>'text','label'=>'Total cost of shipping (with tax)'],
['name'=>'total_products','type'=>'text','label'=>'Total cost of products (no tax)'],
['name'=>'total_products_wt','type'=>'text','label'=>'Total cost of products (with tax)'],
['name'=>'total_wrapping_tax_excl','type'=>'text','label'=>'Total cost of wrapping (no tax)'],
['name'=>'total_wrapping_tax_incl','type'=>'text','label'=>'Total cost of wrapping (with tax)'],
['name'=>'total_paid_tax_excl','type'=>'text','label'=>'Total paid (no tax)'],
['name'=>'total_paid_tax_incl','type'=>'text','label'=>'Total paid (with tax)'],
['name'=>'shop_address','type'=>'textarea','label'=>'Shop address'],
],
'submit' => ['title' => $this->trans('Save', [], 'Admin.Actions'),]
];
</code></pre>
<p>How can I add the invoice_number field to this module so that it updates in the table ps_orders when I put the data and at the same time the rest of the things that the module does?</p>
| 3 | 1,940 |
Use directions service of Google Maps API to show blue line for all routes
|
<pre><code>function placeDistanceMarkers(
coordinates,
in_between_distance,
unit,
departure_time
) {
if (coordinates.length < 2) {
throw new Error("Invalid length of marker coordinates");
}
// the elements are the functions to be called with lat() and lng()
let start_coord = coordinates[0],
end_coord = coordinates[coordinates.length - 1];
let distances = [];
distances.push(0); // init
let marker_index = 0;
// start marker
addMarker(
new google.maps.LatLng(start_coord.lat(), start_coord.lng()),
{ lat: start_coord.lat(), lng: start_coord.lng() },
++marker_index,
departure_time
);
//end marker
addMarker(
new google.maps.LatLng(end_coord.lat(), end_coord.lng()),
{ lat: end_coord.lat(), lng: end_coord.lng() },
++marker_index,
departure_time
);
// calculate distances with the starting coord coordinates[0]
for (let i = 1; i < coordinates.length; i++) {
let d = distance(
{ lat: start_coord.lat(), lng: start_coord.lng() },
{ lat: coordinates[i].lat(), lng: coordinates[i].lng() },
"miles"
);
distances.push(d);
}
let start_distance = 0;
for (let i = 0; i < coordinates.length; i++) {
if (distances[i] - start_distance >= 20) {
start_distance = distances[i];
addMarker(
new google.maps.LatLng(coordinates[i].lat(), coordinates[i].lng()),
{ lat: coordinates[i].lat(), lng: coordinates[i].lng() },
++marker_index,
departure_time
);
}
}
}
function displayRoute2(start, end, departure_time) {
directionsService = new google.maps.DirectionsService();
var request = {
origin: start,
destination: end,
travelMode: "DRIVING",
provideRouteAlternatives: true,
};
directionsService.route(request, function (result, status) {
if (status == "OK") {
console.log(result);
try {
//the directions result which contains multiple routes
directionsResult = result;
let n = directionsResult.routes.length;
//by default , the map displays the first result directions
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setDirections(result);
directionsDisplay.setMap(map);
// place markers
for (let i = 0; i < n; i++) {
placeDistanceMarkers(
[
result.routes[0].legs[0].start_location,
...result["routes"][i]["overview_path"],
result.routes[0].legs[0].end_location,
],
20,
"miles",
departure_time
);
}
fillRouteOptions();
} catch (e) {
console.log(e.toString());
}
}
});
}
</code></pre>
<p>Here is current map I display:
<a href="https://i.stack.imgur.com/5auZW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5auZW.png" alt="enter image description here" /></a></p>
<p>I use above two functions to create map below.
Right now it only displays the blue line for route 0, I would like to have blue line for all the routes.
I am trying to use directionsDisplay.setRouteIndex(i); in the for loop, but this will only display blue line for the last route. Thanks for any help!</p>
| 3 | 1,281 |
while loop issues in expect script
|
<p>I have written a expect script which works as follows:</p>
<ol>
<li>ssh to server1 </li>
<li>From server1 ssh to another server server2</li>
<li>From server2 to server3 and then sudo into a user and run the commands.</li>
</ol>
<p>In the script I read the hostnames and commands to be executed from two files called hostnames.out and commands.out. I used a while loop to iterate through each entries in hostnames.out and run the commands from the commands.out file. </p>
<p>I tested my script with single entry in the hostnames.out it works fine, but when i add multiple lines it is not running the commands on the hostnames from the second line onwards.</p>
<p>The format of the commands.out file is(one command per line):</p>
<pre>
ls -lrt
hostname
whoami
</pre>
<p>The format of the hostnames.out file is:</p>
<pre>
server1 user password server2 user password server3 user password
</pre>
<p>I have attached the script for reference. Please let me know where the problem is.</p>
<pre><code>#!/usr/bin/expect
#####################################################
# script to automate manual works - remote 2 #
# Gopinath #
#####################################################
#Variable declaration:
#Setting variable "prompt" for multiple prompts:
set prompt {[]$#%]\s*$}
#Reading commands list from file:
set fp1 [open "commands_list_2.out" "r"]
set file_data [read $fp1]
close $fp1
# read the hosts file one line at a time
# There should be no new line at the end of the hostnames.out file
set fp [open "hostnames_2.out" "r"]
while { [gets $fp data] >= 0 } {
set ssh1 [lindex $data 0]
set ssh1_usr [lindex $data 1]
set ssh1_pwd [lindex $data 2]
set ods [lindex $data 3]
set ods_usr [lindex $data 4]
set ods_pwd [lindex $data 5]
set serv1 [lindex $data 6]
set serv1_usr [lindex $data 7]
set serv1_pwd [lindex $data 8]
puts $ssh1
puts $ssh1_usr
puts $ssh1_pwd
puts $ods
puts $ods_usr
puts $ods_pwd
puts $serv1
puts $serv1_usr
puts $serv1_pwd
spawn -noecho ssh $ssh1_usr@$ssh1
expect {
"*password:" { send "$ssh1_pwd\r"}
"*route*" { puts "login failed"; exit 1 }
"timed out" { puts "login failed timed out"; exit 1 }
}
expect {
-re $prompt { send "whoami\r"}
}
expect -re $prompt {
send "ssh $ods_usr@$ods\r" }
expect {
"password:" { send "$ods_pwd\r" }
}
}
expect {
-re $prompt { send "whoami\r"}
}
expect -re $prompt {
send "ssh $serv1_usr@$serv1\r" }
expect {
"password:" { send "$serv1_pwd\r" }
}
expect -re $prompt
foreach a [list $file_data] {
send "$a"
expect -re prompt
}
expect -re prompt {
send "exit\r"
}
expect eof
close $fp
`
</code></pre>
<hr>
| 3 | 1,546 |
tizen emulator not running on debian
|
<p>I failed to run Tizen Emulator on debian 8 with intel processor, i'm using Tizen Studio 1.2.
I don't get any error messages on window alert and logs file, I tried to delete and re-create the emulator but it not work.</p>
<p>thanks in advance</p>
<p><strong>Update :</strong> i'm getting error messages from logs on vms</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>08:25:02.331| 9158|I| main| 345|Start emulator...
qemu args: =========================================
"/home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/emulator-x86_64" "-drive" "file=/home/edi/tizen-studio-data/emulator/vms/m-0730-1/emulimg-m-0730-1.x86,if=none,index=0,cache.no-flush=on,id=drive" "-device" "virtio-blk-pci,drive=drive" "-drive" "file=/home/edi/tizen-studio-data/emulator/vms/m-0730-1/swap-m-0730-1.img,if=none,index=1,id=swap" "-device" "virtio-blk-pci,drive=swap" "-enable-kvm" "-device" "vigs,backend=gl,wsi=vigs_wsi" "-device" "yagl,wsi=vigs_wsi,protocol=23" "-smp" "4" "-m" "512" "-device" "virtio-maru-sensor-pci,sensors=accel&geo&gyro&light&proxi&haptic&uv&press&hrm" "-device" "maru-camera,index=0" "-device" "virtio-maru-nfc-pci" "-netdev" "user,id=net0" "-device" "virtio-net-pci,netdev=net0" "-chardev" "file,path=/home/edi/tizen-studio-data/emulator/vms/m-0730-1/logs/emulator.klog,id=con0" "-device" "isa-serial,chardev=con0" "-device" "virtio-serial" "-L" "/home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/data/bios" "-kernel" "/home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/data/kernel/bzImage.x86" "-append" "vm_name=m-0730-1 video=LVDS-1:720x1280-32@60 dpi=295 host_ip=10.0.2.2 console=ttyS0" "-display" "maru_qt,rendering=onscreen,resolution=720x1280,dpi=295" "-device" "virtio-maru-touchscreen-pci,max_point=10" "-device" "AC97" "-device" "virtio-maru-esm-pci" "-device" "virtio-maru-hwkey-pci" "-device" "virtio-maru-evdi-pci" "-device" "virtio-maru-keyboard-pci" "-device" "virtio-maru-vmodem-pci" "-device" "virtio-maru-power-pci" "-device" "codec-pci" "-device" "maru-brightness" "-nodefaults" "-rtc" "base=utc" "-M" "maru-x86-machine" "-usb" "-vga" "none" "-device" "virtio-maru-jack-pci,jacks=earjack&charger&usb"
====================================================
08:25:02.331| 9158|I| main| 348|qemu main start...
08:25:02.333| 9158|I|emul_state| 690|initial display resolution: 720x1280
08:25:02.333| 9158|I|qt5_consol| 171|display density: 295
This application failed to start because it could not find or load the Qt platform plugin "xcb"
in "".
Available platform plugins are: xcb.
Reinstalling the application may fix this problem.
08:25:02.337| 9158|S| backtrace| 191|Got signal: 6(Aborted)
08:25:02.340| 9158|I| backtrace| 182|Backtrace depth is 18
08:25:02.340| 9158|I| backtrace| 184|#0000 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/emulator-x86_64(+0x52db7b) [0x556ce4a58b7b]
08:25:02.340| 9158|I| backtrace| 184|#0001 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/emulator-x86_64(+0x52dc71) [0x556ce4a58c71]
08:25:02.340| 9158|I| backtrace| 184|#0002 /lib/x86_64-linux-gnu/libpthread.so.0(+0xf890) [0x7f3af1504890]
08:25:02.340| 9158|I| backtrace| 184|#0003 /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x37) [0x7f3af117f067]
08:25:02.340| 9158|I| backtrace| 184|#0004 /lib/x86_64-linux-gnu/libc.so.6(abort+0x148) [0x7f3af1180448]
08:25:02.340| 9158|I| backtrace| 184|#0005 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/libQt5Core.so.5(_ZNK14QMessageLogger5fatalEPKcz+0xcf) [0x7f3af28f446f]
08:25:02.340| 9158|I| backtrace| 184|#0006 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/libQt5Gui.so.5(+0xfd81c) [0x7f3af30a081c]
08:25:02.340| 9158|I| backtrace| 184|#0007 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/libQt5Gui.so.5(_ZN22QGuiApplicationPrivate21createEventDispatcherEv+0x2d) [0x7f3af30a089d]
08:25:02.340| 9158|I| backtrace| 184|#0008 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/libQt5Core.so.5(_ZN16QCoreApplication4initEv+0xaa5) [0x7f3af2af1725]
08:25:02.340| 9158|I| backtrace| 184|#0009 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/libQt5Core.so.5(_ZN16QCoreApplicationC1ER23QCoreApplicationPrivate+0x25) [0x7f3af2af18f5]
08:25:02.340| 9158|I| backtrace| 184|#0010 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/libQt5Gui.so.5(_ZN15QGuiApplicationC1ER22QGuiApplicationPrivate+0x9) [0x7f3af30a4949]
08:25:02.340| 9158|I| backtrace| 184|#0011 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/libQt5Widgets.so.5(_ZN12QApplicationC2ERiPPci+0x52) [0x7f3af38d4962]
08:25:02.340| 9158|I| backtrace| 184|#0012 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/emulator-x86_64(qt5_early_prepare+0x126) [0x556ce49fabf6]
08:25:02.340| 9158|I| backtrace| 184|#0013 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/emulator-x86_64(maru_early_qt5_display_init+0x20) [0x556ce49fa520]
08:25:02.340| 9158|I| backtrace| 184|#0014 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/emulator-x86_64(qemu_main+0x4b7a) [0x556ce4a787fa]
08:25:02.340| 9158|I| backtrace| 184|#0015 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/emulator-x86_64(main+0x264) [0x556ce482b594]
08:25:02.340| 9158|I| backtrace| 184|#0016 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) [0x7f3af116bb45]
08:25:02.340| 9158|I| backtrace| 184|#0017 /home/edi/tizen-studio/platforms/tizen-2.4/common/emulator/bin/emulator-x86_64(+0x303f21) [0x556ce482ef21]
Aborted</code></pre>
</div>
</div>
</p>
| 3 | 2,637 |
jquery issue using multiple selector in Animated Circle Menu
|
<p>i am using Animated Circle Menu that works for one menus , but when using multiple one i could not make it work</p>
<p>working one with one selector menu :
<a href="https://jsfiddle.net/gruts8Lv/2/" rel="nofollow">https://jsfiddle.net/gruts8Lv/2/</a></p>
<p>not working with two selector :
<a href="https://jsfiddle.net/6ft5cjj6/7/" rel="nofollow">https://jsfiddle.net/6ft5cjj6/7/</a></p>
<p>working code:</p>
<p>html :</p>
<pre><code><div class='selector' style="width:80px;height:80px">
<ul>
<li>
<input id='c1' type='checkbox'>
<label for='c1' >Menu</label>
</li>
<li>
<input id='c2' type='checkbox'>
<label for='c2' >Menu</label>
</li>
<li>
<input id='c3' type='checkbox'>
<label for='c3' >Menu</label>
</li>
<li>
<input id='c4' type='checkbox'>
<label for='c4' >Menu</label>
</li>
<li>
<input id='c5' type='checkbox'>
<label for='c5' >Menu</label>
</li>
<li>
<input id='c6' type='checkbox'>
<label for='c6' >Menu</label>
</li>
<li>
<input id='c7' type='checkbox'>
<label for='c7' >Menu </label>
</li>
</ul>
<button>Click 1</button>
</div>
</code></pre>
<p>css:</p>
<pre><code>html,
body { height: 100%; }
body {
margin: 0;
background: linear-gradient(#eeeeee, #cccccc);
overflow: hidden;
}
.selector {
position: absolute;
left: 50%;
top: 50%;
width: 140px;
height: 140px;
margin-top: -70px;
margin-left: -70px;
}
.selector,
.selector button {
font-family: 'Oswald', sans-serif;
font-weight: 300;
}
.selector button {
position: relative;
width: 100%;
height: 100%;
padding: 10px;
background: #428bca;
border-radius: 50%;
border: 0;
color: white;
font-size: 20px;
cursor: pointer;
box-shadow: 0 3px 3px rgba(0, 0, 0, 0.1);
transition: all .1s;
}
.selector button:hover { background: #3071a9; }
.selector button:focus { outline: none; }
.selector ul {
position: absolute;
list-style: none;
padding: 0;
margin: 0;
top: -20px;
right: -20px;
bottom: -20px;
left: -20px;
}
.selector li {
position: absolute;
width: 0;
height: 100%;
margin: 0 50%;
-webkit-transform: rotate(-360deg);
transition: all 0.8s ease-in-out;
}
.selector li input { display: none; }
.selector li input + label {
position: absolute;
left: 50%;
bottom: 100%;
width: 0;
height: 0;
line-height: 1px;
margin-left: 0;
background: #fff;
border-radius: 50%;
text-align: center;
font-size: 1px;
overflow: hidden;
cursor: pointer;
box-shadow: none;
transition: all 0.8s ease-in-out, color 0.1s, background 0.1s;
}
.selector li input + label:hover { background: #f0f0f0; }
.selector li input:checked + label {
background: #5cb85c;
color: white;
}
.selector li input:checked + label:hover { background: #449d44; }
.selector.open li input + label {
width: 140px;
height: 140px;
line-height: 140px;
margin-left: -40px;
box-shadow: 0 3px 3px rgba(0, 0, 0, 0.1);
font-size: 14px;
}
</code></pre>
<p>js code: </p>
<pre><code>var angleStart = -360;
// jquery rotate animation
function rotate(li,d) {
$({d:angleStart}).animate({d:d}, {
step: function(now) {
$(li)
.css({ transform: 'rotate('+now+'deg)' })
.find('label')
.css({ transform: 'rotate('+(-now)+'deg)' });
}, duration: 0
});
}
// show / hide the options
function toggleOptions(s) {
$(s).toggleClass('open');
var li = $(s).find('li');
var deg = $(s).hasClass('half') ? 180/(li.length-1) : 360/li.length;
for(var i=0; i<li.length; i++) {
var d = $(s).hasClass('half') ? (i*deg)-90 : i*deg;
$(s).hasClass('open') ? rotate(li[i],d) : rotate(li[i],angleStart);
}
}
$('.selector button').click(function(e) {
toggleOptions($(this).parent());
});
setTimeout(function() { toggleOptions('.selector'); }, 100);
</code></pre>
<p>when i change my html code to add on more selector it does not work pls help me to fix it</p>
| 3 | 1,996 |
Listview item got highlighted on click (not wanted)
|
<p>I've a TabHost with items and I want that they are only highlighted on click.</p>
<p>I had it before and I changed nothing on the ListViews itself but on the TabHost (and I think that shouldn't matter..)</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="at.htl3r.appmosphere.MainActivity$PlaceholderFragment" >
<TabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<ListView
android:id="@+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<ListView
android:id="@+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<ListView
android:id="@+id/tab4"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
</code></pre>
<p>I read some posts how to disable it, but <a href="https://stackoverflow.com/a/12242564/2715720">I don't want to disable it complete</a> because I'll handle a click action</p>
<p>I tried adding <code>choiceMode="none"</code> and a <code>selector</code></p>
<pre><code><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/darkgreen_light" android:state_pressed="true"/>
<item android:drawable="@android:color/transparent" android:state_activated="true"/>
<item android:drawable="@android:color/transparent" android:state_checked="true"/>
<item android:drawable="@android:color/transparent" android:state_selected="true"/>
<item android:drawable="@android:color/transparent"/>
</selector>
</code></pre>
<h1>UPDATE</h1>
<p>better choice: <a href="http://viewpagerindicator.com/" rel="nofollow noreferrer">ViewPagerIndicator</a></p>
| 3 | 1,573 |
Iterate json with multiple values per key for matching pattern: Set dataframe column value depending on value of other column (Faster Python Solution)
|
<p>Below is the Problem statement.</p>
<p><strong>Inputs: -</strong></p>
<ol>
<li>csv containing Time when a particular URL is hit.</li>
<li>json containing multiple url_categories with the matching url patters for each url_categories.</li>
</ol>
<p><strong>Required Output: -</strong>
csv, containing Time, url, and url_category. Where url_category is decided based on URL of input csv and url_patterns mentioned per url_category. If the URL doesn't match any of the patterns then category should be marked as 'Other'.</p>
<p><strong>Objective: -</strong>
Python code should create the required output is a FAST way.</p>
<p>Input csv (simplified) which contains the time when a particular URL is hit, like below.</p>
<pre><code>TIME,URL
11:51,/url3a/partC
12:51,/url6/partA
13:51,/url7/partA/partA/partB
14:51,/url5/partA/partB/part1
15:51,/url3b/partA
16:51,/url8/partA/partB
17:51,/url2a/
18:51,/url5/partA/partB
19:51,/url1/part1/part2
20:51,/url4b/partA
21:51,/url9/partA/partA/partB
22:51,/url2/partA/partB
23:51,/url1a/partD
00:51,/url3/partA/partB
01:51,/url9/partA/partA/partB
02:51,/url4a/
03:51,/url5b/partA/partE
04:51,/url7/partA/partA/partB
05:51,/url1b/part1
</code></pre>
<p>Input json (simplified) describing URL categories with URL patterns, like below.</p>
<pre><code>{
"category1": [ "/url1/part1/part2", "/url1a/", "/url1b/part1" ],
"category2": [ "/url2/partA/partB", "/url2a/", "/url2b/partA" ],
"category3": [ "/url3/partA/partB", "/url3a/", "/url3b/partA" ],
"category4": [ "/url4/partA/partB", "/url4a/", "/url4b/partA" ],
"category5": [ "/url5/partA/partB", "/url5a/", "/url5b/partA" ],
}
</code></pre>
<p>I have a python code which achieves but it is very slow as I'm iterating through each dataframe row and each key & values in the json. <strong>Need a solution which in which the code executes much faster</strong>, as my input csv has many rows and input json also has many url categories and many url patterns associated with each url category.</p>
<pre><code>json1 = '{"category1": ["/url1/part1/part2", "/url1a/", "/url1b/part1"], "category2": ["/url2/partA/partB", "/url2a/", "/url2b/partA"], "category3": ["/url3/partA/partB", "/url3a/", "/url3b/partA"], "category4": ["/url4/partA/partB", "/url4a/", "/url4b/partA"], "category5": ["/url5/partA/partB", "/url5a/", "/url5b/partA"]}'
print(json1)
json2 = json.loads(json1)
print(f"---json2: {json2}; \ntype(json2): {type(json2)}")
df = pd.read_csv(in_csv_path)
print(df)
for i in range(len(df)) :
for key in json2:
for url_pattern in json2[key]:
if str(df.loc[i, "URL"]).find(str(url_pattern)) != -1:
df.loc[i, "CATEGORY"] = key
df.fillna('Other', inplace=True)
print(df)
df.to_csv(out_csv, index=False)
</code></pre>
<p>Below is the output csv.</p>
<pre><code>TIME,URL,CATEGORY
11:51,/url3a/partC ,category3
12:51,/url6/partA,Other
13:51,/url7/partA/partA/partB,Other
14:51,/url5/partA/partB,category5
15:51,/url3b/partA,category3
16:51,/url8/partA/partB,Other
17:51,/url2a/,category2
18:51,/url5/partA/partB,category5
19:51,/url1/part1/part2,category1
20:51,/url4b/partA,category4
21:51,/url9/partA/partA/partB,Other
22:51,/url2/partA/partB,category2
23:51,/url1a/,category1
00:51,/url3/partA/partB,category3
01:51,/url9/partA/partA/partB,Other
02:51,/url4a/,category4
03:51,/url5b/partA,category5
04:51,/url7/partA/partA/partB,Other
05:51,/url1b/part1,category1
</code></pre>
| 3 | 1,826 |
SVG not loading properly
|
<p>I am simply trying to render the svg on the page however it is not loading.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 28 28" xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd" clip-rule="evenodd"
stroke-linejoin="round" stroke-miterlimit="2">
<g transform="matrix(.48451 0 0 .60177 -438.2 27)">
<path fill="none" d="M906.2-44.5h55.3V0h-55.3z" />
<clipPath id="a">
<path d="M906.2-44.5h55.3V0h-55.3z" />
</clipPath>
<g clip-path="url(#a)">
<path
d="M928.5-.4v-5.8l6.3-3 6.3 3v5.5a33.8 33.8 0 01-12.6.3zM916-6.9A42.1 42.1 0 00927-1.6v1a33.4 33.4 0 01-12.5-5.7L916-7zm37.8.3A29.6 29.6 0 01942-1v-5.3l6.2-3 5.5 2.6zm-26-12.1l6.3 2.9v5.8l-6.3 3-6.3-3v-5.8l6.3-3zM907.4-16l6-2.7 6.3 2.9v5.8l-6.1 2.8c-2.9-2.5-5-5.4-6.2-8.8zm53.2-.3a21.4 21.4 0 01-6 8.9l-5.5-2.6v-5.8l6.3-3 5.2 2.5zm-12.3-12l6.2 3v5.8l-6.2 2.9-6.3-3v-5.8l6.3-3zm-13.5 0l6.3 3v5.8l-6.3 2.9-6.2-3v-5.8l6.2-3zm-27.5 0l6.1 3v5.8l-6.3 2.9a18.2 18.2 0 01.2-11.6zm52.2 10.4c.5-1.7.6-3 .6-4.6 0-1.7-.6-3.4-1-4.5l1.5-.7a17.1 17.1 0 01.2 10.5l-1.3-.7zm-31.8-20L934-35v5.8l-6.3 3-6.3-3V-35l6.3-3zm-13.8.2l5.8 2.7v5.8l-6.3 3-5.9-2.8a22 22 0 016.4-8.7zm40.4.3c2.8 2.5 5 5.4 6.2 8.7l-5.1 2.4-6.3-2.9V-35l5.2-2.4zM942-43.6c4.3 1 8.2 3 11.4 5.4l-5.1 2.4-6.3-3v-4.8zm-13.4-.6a34.7 34.7 0 0112.5.4v5l-6.3 3-6.2-3v-5.4zm-1.2 1.5c-2.3.5-4.6 1.2-6.1 2-1.6.6-4 2.1-5.1 3l-1.4-.6a30.1 30.1 0 0112.6-5.7v1.3z"
fill="#404040" />
</g>
</g>
</svg></code></pre>
</div>
</div>
</p>
<p>This is my SVG from my HTML, on the webpage it is loaded.
However it doesn't render to the page.</p>
<p><a href="https://i.stack.imgur.com/QucuS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QucuS.png" alt="enter image description here" /></a></p>
<p>I should add I also have a width and height on the svg of 25px.</p>
| 3 | 1,328 |
ADO.Net retrieving autoincrement values for MS Access database in strongly typed DataSets
|
<p>I write a database client application in C# using MS Access as a DB server.</p>
<p>Users insert new rows using a <code>DataGridView</code>. I need to retrieve autoincrement values of the inserted rows on </p>
<pre><code>this.MyTableTableAdapter.Update(MyDataSet.MyTable)
</code></pre>
<p>operation.</p>
<p>I can't use </p>
<pre><code>this.MyTableTableAdapter.Fill(MyDataSet.MyTable);
</code></pre>
<p>after update operation to refresh the entire table, because the position of required inserted record is lost.</p>
<p>So I read <code>docs.microsoft.com</code>, section "Retrieving Identity or Autonumber Values":</p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-identity-or-autonumber-values" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-identity-or-autonumber-values</a></p>
<p>to understand how to do it.</p>
<p>They write a vague description about it:</p>
<blockquote>
<p>Some database engines, such as the Microsoft Access Jet database engine, do not support output parameters and cannot process multiple statements in a single batch. When working with the Jet database engine, you can retrieve the new AutoNumber value generated for an inserted row by executing a separate SELECT command in an event handler for the RowUpdated event of the DataAdapter.</p>
</blockquote>
<p>I also found a code that must be performed in the event</p>
<p><a href="https://www.safaribooksonline.com/library/view/adonet-cookbook/0596004397/ch04s04.html" rel="nofollow noreferrer">https://www.safaribooksonline.com/library/view/adonet-cookbook/0596004397/ch04s04.html</a></p>
<pre><code>private void OnRowUpdated(object Sender, OleDbRowUpdatedEventArgs args)
{
// Retrieve autonumber value for inserts only.
if(args.StatementType == StatementType.Insert)
{
// SQL command to retrieve the identity value created
OleDbCommand cmd = new OleDbCommand("SELECT @@IDENTITY", da.SelectCommand.Connection);
// Store the new identity value to the CategoryID in the table.
args.Row[CATEGORYID_FIELD] = (int)cmd.ExecuteScalar( );
}
}
</code></pre>
<p>The problem is that VS IDE designer creates strongly typed DataSet without external visibility of DataAdapter object.</p>
<p>It creates TableAdapter that is inherited from Component but not from DataAdapter.</p>
<p>And although it creates a real DataAdapter inside the myTableTableAdapter class, it have protected level.</p>
<pre><code>protected internal global::System.Data.OleDb.OleDbDataAdapter Adapter
</code></pre>
<p>So I can't add any event to the Adapter outside the class myTableTableAdapter.</p>
<p>I assume that the code should be written inside the myTableTableAdapter class
but the code of this class is autogenerated, and file have next comment</p>
<pre><code>//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
</code></pre>
<p>So my custom code could be lost if I add any changes.</p>
<p>So my question is - How to add RowUpdated event for the DataAdapter in strongly typed DataSets?</p>
| 3 | 1,050 |
sql clr c# function to make rest api call
|
<p>I am trying to write a SQL CLR C# function/store procedure to get data from an api server but I'm not getting proper results. Probably I never wrote and never done this. I have searched a lot and found the following code, but this returns data in a full page format where as I want only data in xml format so that I can process it in SQL Server. Also I am passing an url and username password which is Ok, how can I add more parameters to this?</p>
<p>//code</p>
<pre><code>using System;
using System.Data;
using System.Data.SqlClient;
usig System.Data.SqlTypes;
using System.Collections;
using System.Globalization;
// For the SQL Server integration
using Microsoft.SqlServer.Server;
// Other things we need for WebRequest
using System.Net;
using System.Text;
using System.IO;
public partial class Functions
{
// Function to return a web URL as a string value.
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
public static SqlString GET(SqlString uri, SqlString username, SqlString passwd)
{
// The SqlPipe is how we send data back to the caller
SqlPipe pipe = SqlContext.Pipe;
SqlString document;
// Set up the request, including authentication
WebRequest req = WebRequest.Create(Convert.ToString(uri));
if (Convert.ToString(username) != null & Convert.ToString(username) != "")
{
req.Credentials = new NetworkCredential(Convert.ToString(username), Convert.ToString(passwd));
}
((HttpWebRequest)req).UserAgent = "CLR web client on SQL Server";
// Fire off the request and retrieve the response.
// We'll put the response in the string variable "document".
WebResponse resp = req.GetResponse();
Stream dataStream = resp.GetResponseStream();
StreamReader rdr = new StreamReader(dataStream);
document = (SqlString)rdr.ReadToEnd()
// Close up everything...
rdr.Close();
dataStream.Close();
resp.Close();
// .. and return the output to the caller.
return (document);
}
}
</code></pre>
<p>This code returns this result:</p>
<pre><code><html> <head><link rel="alternate" type="text/xml" href="/api.asmx?disco" /> <style type="text/css"> BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } A:hover { color: cc3300; font-weight: bold; text-decoration: underline; } P { color: #000000; margin-top: 0px; margin-bottom: 12px; font-family: Verdana; } pre { background-color: #e5e5cc; padding: 5px; font-family: Courier New; font-size: x-small; margin-top: -5px; border: 1px #f0f0e0 solid; } td { color: #000000; font-family: Verdana; font-size: .7em; } h2 { font-size: 1.5em; font-weight: bold; margin-top: 25px; margin-bottom: 10px; border-top: 1px solid #003366; margin-left: -15px; color: #003366; } h3 { font-size: 1.1em; color: #000000; margin-left: -15px; margin-top: 10px; margin-bottom: 10px; } ul { margin-top: 10px; margin-left: 20px; } ol { margin-top: 10px; margin-left: 20px; } li { margin-top: 10px; color: #000000; } font.value { color: darkblue; font: bold; } font.key { color: darkgreen; font: bold; } font.error { color: darkred; font: bold; } .heading1 { color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal; background-color: #003366; margin-top: 0px; margin-bottom: 0px; margin-left: -30px; padding-top: 10px; padding-bottom: 3px; padding-left: 15px; width: 105%; } .button { background-color: #dcdcdc; font-family: Verdana; font-size: 1em; border-top: #cccccc 1px solid; border-bottom: #666666 1px solid; border-left: #cccccc 1px solid; border-right: #666666 1px solid; } .frmheader { color: #000000; background: #dcdcdc; font-family: Verdana; font-size: .7em; font-weight: normal; border-bottom: 1px solid #dcdcdc; padding-top: 2px; padding-bottom: 2px; } .frmtext { font-family: Verdana; font-size: .7em; margin-top: 8px; margin-bottom: 0px; margin-left: 32px; } .frmInput { font-family: Verdana; font-size: 1em; } .intro { margin-left: -15px; } </style> <title> API Web Service </title></head> <body> <div id="content"> <p class="heading1">API</p><br> <span> <p class="intro">Click <a href="api.asmx">here</a> for a complete list of operations.</p>
</code></pre>
| 3 | 1,899 |
Vuetify using VueI18n results in [Vue warn]: Error in render: "TypeError: Cannot read property '_t' of undefined"
|
<p>Implementing Vue i18n into Vuetify is failing. I think I've followed the guide fairly well. </p>
<p>The below config results in the following error:</p>
<blockquote>
<p>[Vue warn]: Error in render: "TypeError: Cannot read property '_t' of undefined"</p>
</blockquote>
<p><strong>vuetify.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import Vue from 'vue';
import Vuetify from 'vuetify/lib';
import VueI18n from "vue-i18n"
import messages from "../i18n/i18n"
Vue.use(Vuetify)
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'en',
messages
})
export default new Vuetify({
lang: {
t: (key, ...params) => i18n.t(key, params),
}
});
</code></pre>
<p><strong>main.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import Vue from 'vue'
import App from './App.vue'
import router from './router'
import vuetify from './plugins/vuetify';
import store from './store';
Vue.config.productionTip = false
new Vue({
//created,
store,
router,
vuetify: vuetify,
render: h => h(App)
}).$mount('#app')
</code></pre>
<p><strong>i18n folder</strong></p>
<pre><code>/i18n
+i18n.js
/locales
+en.js
</code></pre>
<p><strong>i18n.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import en from './locales/en'
export default {
en
}
</code></pre>
<p><strong>en.js</strong></p>
<pre class="lang-js prettyprint-override"><code>export default {
login: 'Login!'
}
</code></pre>
<p><strong>component usage</strong></p>
<pre><code><v-toolbar-title>
{{ $t('login') }}
</v-toolbar-title>
</code></pre>
<p><strong>Full stack trace</strong></p>
<pre><code>[Vue warn]: Error in render: "TypeError: Cannot read property '_t' of undefined"
found in
---> <Login> at src/views/Login.vue
<App> at src/App.vue
<Root>
warn @ vue.runtime.esm.js:619
vue.runtime.esm.js:1888 TypeError: Cannot read property '_t' of undefined
at Proxy.Vue.$t (vue-i18n.esm.js:192)
at Proxy.render (Login.vue?81ae:33)
at VueComponent.Vue._render (vue.runtime.esm.js:3548)
at VueComponent.updateComponent (vue.runtime.esm.js:4066)
at Watcher.get (vue.runtime.esm.js:4479)
at new Watcher (vue.runtime.esm.js:4468)
at mountComponent (vue.runtime.esm.js:4073)
at VueComponent.push../node_modules/vue/dist/vue.runtime.esm.js.Vue.$mount (vue.runtime.esm.js:8415)
at init (vue.runtime.esm.js:3118)
at merged (vue.runtime.esm.js:3301)
</code></pre>
<p>My goal is to extend Vuetify locals under VueI18n as answered here: <a href="https://stackoverflow.com/questions/59821458/use-both-vuetify-and-vue-i18n-translations">Use both Vuetify and Vue-i18n translations</a>.</p>
<p>If I move the VueI18n definition and pass it to Vue constructor, this works. </p>
<p>What is the preferred way to configure this functionality? </p>
| 3 | 1,238 |
Hover on column and rows, with multiple background colors
|
<p>I know this can be done with rows, but I haven't been able to make it also work for columns. I need to be able to color code my columns, but keep the same hover color across all columns. Below is the code I have so far, I need to color the background on the 1st column grey, and leave everything else the same white. While keeping the same hover color across all rows and columns. Hope that makes sense!</p>
<p><a href="https://codepen.io/fazulk/pen/LzvKPo" rel="nofollow noreferrer">Codepen</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.grey-column {
background-color: grey;
}
.data-table {
overflow: hidden;
border: solid black;
border-collapse: collapse;
border-width: 1px 2px 2px 1px;
}
.data-cell {
padding: 10px;
font-size: 14px;
position: relative;
border: solid black;
border-width: 1px 1px 1px 1px;
}
.data-row:hover {
padding: 10px;
background-color: #ffa;
}
.data-cell::before {
content: "";
position: absolute;
top: 0;
left: -5000px;
width: 10000px;
height: 100%;
z-index: -10;
}
.data-cell:hover::after {
content: "";
position: absolute;
background-color: #ffa;
left: 0;
top: -5000px;
height: 10000px;
width: 100%;
z-index: -5;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="data-table">
<tbody>
<tr class="data-row">
<td class="grey-column">I should change to hover color</td>
<td class="data-cell">Cell 2</td>
<td class="data-cell">Cell 3</td>
<td class="data-cell">Cell 4</td>
</tr>
<tr class="data-row">
<td class="grey-column">I should change to hover color</td>
<td class="data-cell">Cell 2</td>
<td class="data-cell">Cell 3</td>
<td class="data-cell">Cell 4</td>
</tr>
<tr class="data-row">
<td class="grey-column">I should change to hover color</td>
<td class="data-cell">Cell 2</td>
<td class="data-cell">Cell 3</td>
<td class="data-cell">Cell 4</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p>
| 3 | 1,031 |
Neural network is not being trained, cross-entropy stays about the same
|
<p>I have written the following multilayer perceptron model in TensorFlow, but it is not training. The accuracy stays around 9%, which is equivalent to random guessing, and cross-entropy stay around 2.56 and does not vary much.</p>
<p>The architecture is as follows:</p>
<pre><code>def create_model(fingerprint_input, model_settings, is_training):
if is_training:
dropout_prob = tf.placeholder(tf.float32, name='dropout_prob')
fingerprint_size = model_settings['fingerprint_size']
label_count = model_settings['label_count']
weights_1 = tf.Variable(tf.truncated_normal([fingerprint_size, 128], stddev=0.001))
weights_2 = tf.Variable(tf.truncated_normal([128, 128], stddev=0.001))
weights_3 = tf.Variable(tf.truncated_normal([128, 128], stddev=0.001))
weights_out = tf.Variable(tf.truncated_normal([128, label_count], stddev=0.001))
bias_1 = tf.Variable(tf.zeros([128]))
bias_2 = tf.Variable(tf.zeros([128]))
bias_3 = tf.Variable(tf.zeros([128]))
bias_out = tf.Variable(tf.zeros([label_count]))
layer_1 = tf.matmul(fingerprint_input, weights_1) + bias_1
layer_1 = tf.nn.relu(layer_1)
layer_2 = tf.matmul(layer_1, weights_2) + bias_2
layer_2 = tf.nn.relu(layer_2)
layer_3 = tf.matmul(layer_2, weights_3) + bias_3
layer_3 = tf.nn.relu(layer_3)
logits = tf.matmul(layer_3, weights_out) + bias_out
if is_training:
return logits, dropout_prob
else:
return logits
</code></pre>
<p>It takes the input size as <code>fingerprint_size</code> and the labels size as well as <code>label_count</code>. It has three hidden layers with 128 neurons each. I'm following the TensorFlow example on a speech data set, which provides a framework for everything else. In the documentation, all I needed to do is to include my own neural network architecture and my method should have those arguments defined and return the logits.</p>
<p>When I trained another predefined architecture, with the same inputs and output, the neural network trains. But this one is not training. Here is one predefined architecture:</p>
<pre><code>def create_single_fc_model(fingerprint_input, model_settings, is_training):
if is_training:
dropout_prob = tf.placeholder(tf.float32, name='dropout_prob')
fingerprint_size = model_settings['fingerprint_size']
label_count = model_settings['label_count']
weights = tf.Variable(
tf.truncated_normal([fingerprint_size, label_count], stddev=0.001))
bias = tf.Variable(tf.zeros([label_count]))
logits = tf.matmul(fingerprint_input, weights) + bias
if is_training:
return logits, dropout_prob
else:
return logits
</code></pre>
<p>The learning rate are 0.001 for the first 15000 steps and 0.0001 for the last 3000 steps. These are the defaults. I also tried with 0.01 and 0.001, but the same result. I think the problem is somewhere in the above implementation.</p>
<p>Any idea?</p>
<p>Thank you in advance!</p>
| 3 | 1,045 |
Can't get jquery-masonry to work
|
<p>HTML</p>
<pre><code><div id="container">
<div class="item">
<p>AAAAAAAAA amet tail frankfurter brisket, meatloaf beef ribs doner pork prosciutto ball tip rump tenderloin tongue. Pastrami fatback beef, sausage beef ribs venison tenderloin swine. Fatback leberkas kielbasa drumstick pork venison beef frankfurter. Turducken rump capicola, spare ribs leberkas brisket pork belly ball tip ground round. Tongue strip steak beef ribs shoulder.</p>
<p>Bacon ipsum dolor sit amet tail frankfurter brisket, meatloaf beef ribs doner pork prosciutto ball tip rump tenderloin tongue. Pastrami fatback beef, sausage beef ribs venison tenderloin swine. Fatback leberkas kielbasa drumstick pork venison beef frankfurter. Turducken rump capicola, spare ribs leberkas brisket pork belly ball tip ground round. Tongue strip steak beef ribs shoulder.</p>
</div>
<div class="item">
<p>BBBBBBBBmet tail frankfurter brisket, meatloaf beef ribs doner pork prosciutto ball tip rump tenderloin tongue. Pastrami fatback beef, sausage beef ribs venison tenderloin swine. Fatback leberkas kielbasa drumstick pork venison beef frankfurter. Turducken rump capicola, spare ribs leberkas brisket pork belly ball tip ground round. Tongue strip steak beef ribs shoulder.</p>
<p>Bacon ipsum dolor sit amet tail frankfurter brisket, meatloaf beef ribs doner pork prosciutto ball tip rump tenderloin tongue. Pastrami fatback beef, sausage beef ribs venison tenderloin swine. Fatback leberkas kielbasa drumstick pork venison beef frankfurter. Turducken rump capicola, spare ribs leberkas brisket pork belly ball tip ground round. Tongue strip steak beef ribs shoulder.</p>
<p>Bacon ipsum dolor sit amet tail frankfurter brisket, meatloaf beef ribs doner pork prosciutto ball tip rump tenderloin tongue. Pastrami fatback beef, sausage beef ribs venison tenderloin swine. Fatback leberkas kielbasa drumstick pork venison beef frankfurter. Turducken rump capicola, spare ribs leberkas brisket pork belly ball tip ground round. Tongue strip steak beef ribs shoulder.</p>
<p>Bacon ipsum dolor sit amet tail frankfurter brisket, meatloaf beef ribs doner pork prosciutto ball tip rump tenderloin tongue. Pastrami fatback beef, sausage beef ribs venison tenderloin swine. Fatback leberkas kielbasa drumstick pork venison beef frankfurter. Turducken rump capicola, spare ribs leberkas brisket pork belly ball tip ground round. Tongue strip steak beef ribs shoulder.</p><p>Bacon ipsum dolor sit amet tail frankfurter brisket, meatloaf beef ribs doner pork prosciutto ball tip rump tenderloin tongue. Pastrami fatback beef, sausage beef ribs venison tenderloin swine. Fatback leberkas kielbasa drumstick pork venison beef frankfurter. Turducken rump capicola, spare ribs leberkas brisket pork belly ball tip ground round. Tongue strip steak beef ribs shoulder.</p>
</div>
etc....
</code></pre>
<p>CSS</p>
<pre><code>body {
background-color: red;
}
.container{ width:940px; margin:0px auto;}
.item {
width: 220px;
margin: 10px;
float: left;
padding: 5px;
background-color: white;
}
</code></pre>
<p>I can't figure out what I am doing wrong. I even pasted the default masontry code into my editor (<a href="http://jsfiddle.net/desandro/LDEGk/" rel="nofollow">http://jsfiddle.net/desandro/LDEGk/</a>) and it was messing up.</p>
<p><a href="http://jsfiddle.net/ntzMr/" rel="nofollow">http://jsfiddle.net/ntzMr/</a></p>
<p>These are my script files located in the body tag (the .js file is located in the root folder):</p>
<pre><code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="/jquery.masonry.min.js"></script>
</code></pre>
| 3 | 1,281 |
How can I create a 50/50 vertical layout with stacked GridViews?
|
<p>One of my DialogFragments implements two equal-sized GridViews, one stacked on top of the other. Ideally, my layout would look like this (as seen in Android Studio):
<img src="https://i.stack.imgur.com/Hn433.png" alt="The layout as seen in Android Studio"></p>
<p>Unfortunately, when I load up the layout on an actual Android device, I get something like this:
<img src="https://i.stack.imgur.com/lE0F7.png" alt="The same layout on Android"></p>
<p>When the <strong>Kanji</strong> GridView is empty, it's completely invisible. Additionally, its height varies depending on the number of elements it has to display. How can I force the bottom GridView to fill 50% of the height as per the layout seen in Android Studio, even when it's empty?</p>
<p>Here is the XML for this particular layout:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/kanji_lookup_root"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:focusableInTouchMode="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ProgressBar
android:layout_width="32dp"
android:layout_height="32dp"
android:id="@+id/progress_bar"
android:layout_toStartOf="@+id/search_box_kanji"
android:visibility="gone"
android:indeterminate="true"
android:layout_centerVertical="true"/>
<SearchView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="@id/search_box_kanji"
android:queryHint="@string/menu_search_hint"
android:iconifiedByDefault="false"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
style="@style/EntryDetailsHeader"
android:text="@string/components" />
<com.tonicartos.widget.stickygridheaders.StickyGridHeadersGridView
android:id="@+id/grid_components"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="9"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
style="@style/EntryDetailsHeader"
android:text="@string/kanji" />
<GridView
android:id="@+id/grid_kanji"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:numColumns="9"/>
</LinearLayout>
</LinearLayout>
</code></pre>
<p>(By the way I'm using the <a href="https://github.com/TonicArtos/StickyGridHeaders" rel="nofollow noreferrer">StickyGridHeaders library</a> for the upper <strong>Components</strong> GridView)</p>
| 3 | 1,439 |
wrong url is not triggering error using combine
|
<p>I am using the code here. But I couldn't figure out how to use the code here.</p>
<p><strong>Stack Overflow <a href="https://stackoverflow.com/questions/65126447/error-is-not-triggering-on-url-session-using-combine">link</a></strong></p>
<p>How can I run this function with combine?
How can I run a function with return type <code>AnyPublisher<T, NetworkingError></code> with combine and catch errors.
my apikey is faulty and i want to catch this error.</p>
<p><strong>Function:</strong></p>
<pre><code>private func performOperation<T: Decodable>(requestUrl: URLRequest, responseType: T.Type) -> AnyPublisher<T, NetworkingError> {
URLSession.shared.dataTaskPublisher(for: requestUrl)
.jsonDecodingPublisher(type: T.self)
}
</code></pre>
<p><strong>My Code:</strong></p>
<pre><code>class MovieService {
private let baseURL = "https://api.themoviedb.org/3/movie"
private let apiKey = "594b8eb4999a8b44ad5136ee3ed1ebdb31"
private let language = "language=en-US"
var anyCancellable = Set<AnyCancellable>()
init() { }
func loadAllMovie(categoryType: CategoryType, page: Int) -> Future<Movie, Error> {
if let url = URL(string: baseURL + "/" + categoryType.rawValue + "?" + "api_key=" + apiKey + "&" + language + "&" + "page=" + "\(page)") {
let foo = performOperation(requestUrl: URLRequest(url: url), responseType: Movie.self)
foo
.receive(on: DispatchQueue.main)
.sink { error in
switch error {
case .finished:
print("end")
case .failure(let error):
print(error.localizedDescription)
}
} receiveValue: { movie in
print(movie)
}
.store(in: &anyCancellable)
} else {
print("url sıkıntılı")
}
if let data = getData(from: baseURL, categoryType: categoryType, page: page) {
do {
let bookDecoder = try JSONDecoder().decode(Movie.self, from: data)
return Future { promixe in
promixe(.success(bookDecoder))
}
}catch {
debugPrint(error.localizedDescription)
debugPrint("errrrr: \(error)")
print("olmadı")
}
}
return Future{ _ in }
}
private func performOperation<T: Decodable>(requestUrl: URLRequest, responseType: T.Type) -> AnyPublisher<T, NetworkingError> {
URLSession.shared.dataTaskPublisher(for: requestUrl)
.jsonDecodingPublisher(type: T.self)
}
private func getData(from urlString: String, categoryType: CategoryType, page: Int) -> Data? {
guard let url = URL(string: urlString + "/" + categoryType.rawValue + "?" + "api_key=" + apiKey + "&" + language + "&" + "page=" + "\(page)") else {
fatalError("Couldn't load URL from provided string.")
}
do {
return try Data(contentsOf: url)
} catch {
debugPrint("Couldn't load data from URL:\n\(error)")
return nil
}
}
}
enum NetworkingError: Error {
case decoding(DecodingError)
case incorrectStatusCode(Int)
case network(URLError)
case nonHTTPResponse
case unknown(Error)
}
extension Publisher {
func mapErrorToNetworkingError() -> AnyPublisher<Output, NetworkingError> {
mapError { error -> NetworkingError in
switch error {
case let decodingError as DecodingError:
return .decoding(decodingError)
case let networkingError as NetworkingError:
return networkingError
case let urlError as URLError:
return .network(urlError)
default:
return .unknown(error)
}
}
.eraseToAnyPublisher()
}
}
extension URLSession.DataTaskPublisher {
func emptyBodyResponsePublisher() -> AnyPublisher<Void, NetworkingError> {
httpResponseValidator()
.map { _ in Void() }
.eraseToAnyPublisher()
}
}
extension URLSession.DataTaskPublisher {
func httpResponseValidator() -> AnyPublisher<Output, NetworkingError> {
tryMap { data, response in
guard let httpResponse = response as? HTTPURLResponse else { throw NetworkingError.nonHTTPResponse }
let statusCode = httpResponse.statusCode
guard (200..<300).contains(statusCode) else { throw NetworkingError.incorrectStatusCode(statusCode) }
return (data, httpResponse)
}
.mapErrorToNetworkingError()
}
func httpResponseValidatorDataPublisher() -> AnyPublisher<Data, NetworkingError> {
httpResponseValidator()
.map(\.data)
.eraseToAnyPublisher()
}
func jsonDecodingPublisher<T:Decodable>(type: T.Type) -> AnyPublisher<T, NetworkingError> {
httpResponseValidatorDataPublisher()
.decode(type: T.self, decoder: JSONDecoder())
.mapErrorToNetworkingError()
}
}
</code></pre>
| 3 | 2,707 |
Unpermitted parameters in Rails strong params from related Model on create
|
<p>I'm using a form in Rails to create an instance of one Model and create a join table to another model on create. In my <code>Accounts</code> controller, after verifying the new instance of <code>Account</code> has been created, I create a new join table based on checkboxes chosen in the form from another model. </p>
<p>Here is my code: </p>
<p>Models: </p>
<pre><code>class Account < ApplicationRecord
has_many :account_authorizations
has_many :authorizations, through: :account_authorizations
accepts_nested_attributes_for :authorizations
end
</code></pre>
<pre><code>class Authorization < ApplicationRecord
has_many :account_authorizations
has_many :accounts, through: :account_authorizations
end
</code></pre>
<pre><code>class AccountAuthorization < ApplicationRecord
belongs_to :account
belongs_to :authorization
end
</code></pre>
<p>My <code>Accounts</code> controller: </p>
<pre><code>class AccountsController < ApplicationController
before_action :find_account, only: [:show, :update, :destroy]
def index
@accounts = Account.all
end
def show
end
def new
@authorizations = Authorization.all
end
def create
byebug
@account = Account.new(account_params)
if @account.save
authorization_ids = params.permit![:authorization][:ids]
authorization_ids.each do |auth_id|
AccountAuthorization.create(authorization_id: auth_id, account_id: params[:id]) if !auth_id.empty?
end
flash[:notice] = "Account created sucsessfully"
redirect_to account_path(@account)
else
flash[:error] = @item.errors.full_messages.to_sentence
render :new
end
end
def edit
end
def update
@account = Account.update(account_params)
if @account.valid?
flash[:notice] = "Account created sucsessfully"
redirect_to accounts_path(@account)
else
flash[:error] = @item.errors.full_messages.to_sentence
render :edit
end
end
def destroy
@account.delete
redirect_to accounts_path
end
private
def find_account
@account = Account.find(params[:id])
end
def account_params
params.permit(
:account_name,
:account_address_line1,
:account_address_line2,
:account_city,
:account_state,
:account_zipcode,
:account_ppu,
:account_notes,
:contact_first_name,
:contact_last_name,
:contact_phone,
:contact_email
)
end
end
</code></pre>
<p>I've tried using .permit! on params but this does not allow the the ids from <code>Authorization</code> to pass into a new join instance of <code>AccountAuthorization</code>. </p>
<p>The attributes that don't pass are:</p>
<pre><code>Unpermitted parameters: :authenticity_token, :authorization, :commit
</code></pre>
<p>I've also tried putting those in the permit hash in the strong_params method. </p>
<p>** UPDATE **</p>
<p>My Views page with <code>form</code>: </p>
<pre><code><% states = [ 'AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DC', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MH', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'MP', 'OH', 'OK', 'OR', 'PA' 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT' 'VA', 'WA', 'WV', 'WI', 'WY'] %>
<% ppu = ['Employment', 'Insurance', 'Law Enforement'] %>
<div class="row justify-content-center">
<div class="col-lg-16">
<h3>Create New Account</h3>
</div>
</div>
<div class="row justify-content-center">
<div class="col-lg-16">
<%= form_with(url: accounts_path, model: @account, local: true) do |f| %>
<%= f.text_field :account_name, class: "form-control", placeholder: "Account Name" %>
<%= f.text_field :account_address_line1, class: "form-control", placeholder: "address line 1" %>
<%= f.text_field :account_address_line2, class: "form-control", placeholder: "address line 2" %>
<%= f.text_field :account_city, class: "form-control", placeholder: "account city" %>
<%= f.select :account_state, options_for_select(states), { :prompt => true }, class: "form-control", include_blank: true, placeholder: "state" %>
<%= f.text_field :account_zipcode, class: "form-control", placeholder: "account zipcode" %>
<%= f.text_field :contact_first_name, class: "form-control", placeholder: "contact first name" %>
<%= f.text_field :contact_last_name, class: "form-control", placeholder: "contact last name" %>
<%= f.text_field :contact_phone, class: "form-control", placeholder: "conact phone" %>
<%= f.text_field :contact_email, class: "form-control", placeholder: "contact email" %>
<%= f.select :account_ppu, options_for_select(ppu), { :prompt => true }, class: "form-control", include_blank: true, placeholder: "ppu" %>
<%= f.text_area :account_notes, class: "form-control", placeholder: "Notes..." %>
<div class="d-flex justify-content-between flex-wrap">
<%= f.fields_for :authorization do |auth| %>
<div class="order-3 p-2 bd-highlight">
<%= auth.collection_check_boxes :ids, Authorization.all, :id, :auth_name %>
</div>
<% end %>
</div>
<%= f.submit "Create", class: 'btn btn-success' %>
<% end %>
</div>
</div>
</code></pre>
| 3 | 2,373 |
Reducing nested array
|
<p>I am receiving this JSON from my backend and i need to work out the count of "concrete_compressive_cylinder_100"'s where picked_up = false</p>
<p>concrete_samples (can be multiple per work order) can be null ( key is always present )</p>
<p>sample_specimens ( 1 per concrete_sample) can be null ( key is always present )</p>
<p>concrete_compressive_cylinder_100 ( null to 500 per sample_specimens )</p>
<pre><code>{
"uuid":"4ad7bfe1-48d6-488c-bfaf-33f7189a41d7",
"org_workorder_id":1000,
"concrete_samples":[
{
"uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
"workorder_uuid":"4ad7bfe1-48d6-488c-bfaf-33f7189a41d7",
"org_sample_id":5001,
"sample_specimens":{
"concrete_compressive_cylinder_100":[
{
"uuid":"b9ef3a8a-2945-41e6-a34d-d90d1bd64819",
"sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
"picked_up":true
},
{
"uuid":"d43f15b3-2208-43de-8fff-8d237c6918f9",
"sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
"picked_up":true
},
{
"uuid":"472f832a-6f07-4af6-97ea-e6dc7b9b3799",
"sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
"picked_up":true
}
],
"concrete_compressive_cylinder_200":[
{
"uuid":"d659d058-e4ec-4f72-9d73-9ea98295715a",
"sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
"picked_up":true
},
{
"uuid":"777372e0-3e58-4292-bae4-bec84dfe1402",
"sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
"picked_up":true
},
{
"uuid":"f63f7102-7673-4e71-97e5-2d85e0c1a93d",
"sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
"picked_up":true
}
]
}
},
{
"uuid":"61138cf3-0c49-4495-8a89-533c0a6e50bc",
"workorder_uuid":"4ad7bfe1-48d6-488c-bfaf-33f7189a41d7",
"org_sample_id":5002,
"sample_specimens":{
"concrete_compressive_cylinder_100":null,
"concrete_compressive_cylinder_200":null
}
}
]
}
</code></pre>
<p>I've gotten this far but it dosen't really work and now im more confused some guidance would be great</p>
<pre><code> const out = res.data.concrete_samples.reduce((acc, sample) => {
const { sample_specimens } = sample;
const concrete_compressive_cylinder_100 = Object.keys(sample_specimens)["concrete_compressive_cylinder_100"];
const specimens = concrete_compressive_cylinder_100.map(obj => {
obj.picked_up ? console.log("picked up") : console.log("Not pickedn up")
});
}, []);
</code></pre>
| 3 | 1,815 |
cant upload to datastore in ckan 2.5.1: using postgres user instead of configured one
|
<p>I followed the instructions to install ckan as a package on Ubuntu 12.04 LTS. </p>
<p>I also configured the datastore extension. The databases have been created and the default users and passwords have been configured in /etc/ckan/default/production.ini</p>
<p>My problem is that every time I want to upload a dataset to the DataStore (using the button "Upload to DataStore") it first seems that everything works fine. But if I click somewhere else and click on the DataStore again I get the following red error box:</p>
<blockquote>
<p>Error: CKAN DataStore bad response. Status code: 409 Conflict. At:
<a href="http://xubuntu12ltsckan/api/3/action/datastore_create" rel="nofollow">http://xubuntu12ltsckan/api/3/action/datastore_create</a>. HTTP status
code: 409 Response: {"help":
"<a href="http://xubuntu12ltsckan/api/3/action/help_show?name=datastore_create" rel="nofollow">http://xubuntu12ltsckan/api/3/action/help_show?name=datastore_create</a>",
"success": false, "error": {"fields": ["\"2016-01-07 14:35:12 ERROR :
Error connecting to the server: FATAL: password... Requested URL:
hhttp://xubuntu12ltsckan/api/3/action/datastore_create</p>
</blockquote>
<p>(Third url mangled because I don't have the reputation to post more than 2 URLs) </p>
<p>The /var/log/apache2/datapusher.error.log lists these lines:</p>
<pre><code>Fri Jan 22 13:38:24 2016] [error] /usr/lib/ckan/datapusher/lib/python2.7/site-packages/sqlalchemy/sql/sqltypes.py:185: SAWarning: Unicode type received non-unicode bind param value '42e50497-2231-4c86-b8db-d...'. (this warning may be suppressed after 10 occurrences)
[Fri Jan 22 13:38:24 2016] [error] (util.ellipses_string(value),))
[Fri Jan 22 13:38:24 2016] [error] Fetching from: http://xubuntu12ltsckan/dataset/f4f9e859-fa6a-4257-8727-32358b448864/resource/d938a82f-95f7-4abd-b982-b32174dfa584/download/pgadmin.log
[Fri Jan 22 13:38:24 2016] [error] Deleting "d938a82f-95f7-4abd-b982-b32174dfa584" from datastore.
[Fri Jan 22 13:38:24 2016] [error] Determined headers and types: [{'type': u'text', 'id': u'2016-01-07 14:35:12 ERROR : Error connecting to the server: FATAL: password authentication failed for user "postgres"'}]
[Fri Jan 22 13:38:24 2016] [error] Saving chunk 0
[Fri Jan 22 13:38:24 2016] [error] Job "push_to_datastore (trigger: RunTriggerNow, run = True, next run at: None)" raised an exception
[Fri Jan 22 13:38:24 2016] [error] Traceback (most recent call last):
[Fri Jan 22 13:38:24 2016] [error] File "/usr/lib/ckan/datapusher/lib/python2.7/site-packages/apscheduler/scheduler.py", line 512, in _run_job
[Fri Jan 22 13:38:24 2016] [error] retval = job.func(*job.args, **job.kwargs)
[Fri Jan 22 13:38:24 2016] [error] File "/usr/lib/ckan/datapusher/src/datapusher/datapusher/jobs.py", line 387, in push_to_datastore
[Fri Jan 22 13:38:24 2016] [error] records, api_key, ckan_url)
[Fri Jan 22 13:38:24 2016] [error] File "/usr/lib/ckan/datapusher/src/datapusher/datapusher/jobs.py", line 203, in send_resource_to_datastore
[Fri Jan 22 13:38:24 2016] [error] check_response(r, url, 'CKAN DataStore')
[Fri Jan 22 13:38:24 2016] [error] File "/usr/lib/ckan/datapusher/src/datapusher/datapusher/jobs.py", line 137, in check_response
[Fri Jan 22 13:38:24 2016] [error] request_url=request_url, response=response.text)
[Fri Jan 22 13:38:24 2016] [error] HTTPError
</code></pre>
<p>So my problem is that for some reason I don't know ckan tries to connect to the postgres database with the postgres user.</p>
<p>My production.ini instead looks like this:</p>
<pre><code>## Database Settings
sqlalchemy.url = postgresql://ckan_default:xxx@localhost/ckan_default
ckan.datastore.write_url = postgresql://ckan_default:xxx@localhost/datastore_default
ckan.datastore.read_url = postgresql://datastore_default:xxx@localhost/datastore_default
</code></pre>
<p>There is no reference to the default database admin user in this file. The role "ckan_default" has CREATE/TEMP/CONNECT privileges and "datastore_default" has CONNECT privileges on the datastore_default database.</p>
<p>I don't see any access constraints here. Can somebody help me to solve this issue?</p>
| 3 | 1,498 |
Laravel 4, Eloquents pagination method
|
<p>Hello! I am having a problem when trying to use the paginate method on an eloquent model. The problem being that calling <code>{{ $model->links() }}</code> in my view file will throw me a <code>Call to undefined method Illuminate\Database\Query\Builder::links()</code> which didn't really get me anywhere due to it working perfectly on another view file.</p>
<p>Controller.php</p>
<pre><code>$data = Routine::whereHas('measurements', function($q)
{
$fra = str_replace("/","-", Input::get('fraDato'));
$fra = date('Y-m-d', strtotime($fra));
$til = str_replace("/","-", Input::get('tilDato'));
$til = date('Y-m-d', strtotime($til));
$q->whereBetween('date', array($fra, $til));
})->with('emps')->orderBy('date', 'time', 'title')->paginate(5);
return View::make('sok')
->with('title', 'Søk')
->with('date', $date)
->with('data', $data);
</code></pre>
<p>sok.blade.php</p>
<pre><code>@if(isset($data))
<table>
<tr>
<td>ID</td>
<td>Tittel</td>
<td>Verdi</td>
<td>Ansatt ID</td>
<td>Dato</td>
<td>Tid</td>
<td>Basseng</td>
</tr>
@foreach($data as $data)
<tr>
<td>{{ $data->id }}</td>
<td>{{ $data->measurements[0]->title }}</td>
<td>{{ $data->value }}</td>
<td>{{ $data->emps->user_name }}</td>
<td>{{ date('d/m/Y', strtotime($data->date)) }}</td>
<td>{{ $data->time }}</td>
@foreach($data->measurements as $measurement)
<td>{{ $measurement->pivot->pool_id }}</td>
@endforeach
<td>{{ HTML::linkRoute('edit_data', 'Rediger', $data->id) }}</td>
<td>{{ HTML::linkRoute('delete_confirm', 'Slett', $data->id) }}
</td>
</tr>
@endforeach
{{ $data->links() }}
</code></pre>
<p>Thanks!</p>
| 3 | 1,516 |
Trying to add a JComboBox dropdown into a JTextField area
|
<p>I have spent many hours digging around the web and cannot seem to find a straightforward answer or method to add a dropdown selection into my main panel that houses the various text fields, in this case, I am trying to add a paint color selection to the panel so that color can then be used as a variable in determining cost.</p>
<p>The closest I have come so far is having a combo box popup in a new window but then was unable to retrieve the selection.</p>
<pre><code>package paintestimator;
import java.lang.String;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Component;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.PopupMenu;
import javax.swing.JComboBox;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PaintEstimator extends JFrame
{
private JTextField wallHeight = new JTextField(3);
private JTextField wallWidth = new JTextField(3);
private JTextField wallArea = new JTextField(3);
private JTextField gallonsNeeded = new JTextField(3);
private JTextField cansNeeded = new JTextField(3);
private JTextField paintTime = new JTextField(3);
private JTextField sColor = new JTextField(3);
private JTextField matCost = new JTextField(3);
private JTextField laborCost = new JTextField(3);
//Josh
public PaintEstimator()
{
JButton CalcChangeBTN = new JButton("Calculate");
JButton ClearBTN = new JButton("Clear");
JButton ChoiceA = new JButton("Paint Color");
//JComboBox vendorBTN = (new JComboBox());
ChoiceA.addActionListener(new ChoiceAListener());
CalcChangeBTN.addActionListener(new CalcChangeBTNListener());
ClearBTN.addActionListener(new ClearBTNListener());
wallHeight.setEditable(true);
wallWidth.setEditable(true);
wallArea.setEditable(false);
gallonsNeeded.setEditable(false);
paintTime.setEditable(false);
cansNeeded.setEditable(false);
sColor.setEditable(true);
matCost.setEditable(false);
laborCost.setEditable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(16, 3, 0, 0));
// need cost of paint array to set equations for material cost
// need combobox arrays for both color and cost
// vendor selection combo box sets array field for cost/color
mainPanel.add(new JLabel("Please enter wall height in feet"));
mainPanel.add(wallHeight);
mainPanel.add(new JLabel("please enter wall width in feet"));
mainPanel.add(wallWidth);
//box to show chosen color
//mainPanel.add(new JLabel("Color Chosen"));
// mainPanel.add(sColor);
mainPanel.add(new JLabel("wall area"));
mainPanel.add(wallArea);
mainPanel.add(new JLabel("Gallons Needed"));
mainPanel.add(gallonsNeeded);
mainPanel.add(new JLabel("Number of cans Needed"));
mainPanel.add(cansNeeded);
mainPanel.add(new JLabel("Time to paint in Hours"));
mainPanel.add(paintTime);
mainPanel.add(new JLabel("Cost of Labor"));
mainPanel.add(laborCost);
mainPanel.add(new JLabel("Total Cost of Material"));
mainPanel.add(matCost);
mainPanel.add( new JLabel("Select a Color"));
mainPanel.add (ChoiceA);
// mainPanel.add(sColor);
// Select<String> select = new Select<>();
//select.setLabel("Sort by");
//select.setItems("Most recent first", "Rating: high to low",
// "Rating: low to high", "Price: high to low", "Price: low to high");
//select.setValue("Most recent first");
// mainPanel.add(select);
mainPanel.add(CalcChangeBTN);
mainPanel.add(ClearBTN);
// mainPanel.add(ChoiceA);
setContentPane(mainPanel);
pack();
setTitle("Paint Estimator Tool");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
//Josh
class CalcChangeBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try
{
final double paintCvrGal = 320.0;
final double gallonsPerCan = 1.0;
double h = Integer.parseInt(wallHeight.getText());
double w = Integer.parseInt(wallWidth.getText());
double a = h * w;
double c = ((a / paintCvrGal) * gallonsPerCan);
double n = (c / gallonsPerCan);
double p = (int) ((a * 0.76) / 60);
double l = Integer.parseInt(laborCost.getText());
double labCost = l * p;
// double mc = c * CostofPaint
wallArea.setText(String.valueOf(a));
String wallArea = String.valueOf(a);
gallonsNeeded.setText(String.valueOf(c));
String gallonsNeeded = Double.toString(c);
cansNeeded.setText(String.valueOf(n));
String cansNeeded = Double.toString(n); // still need refine decimal point to #.0
(one decimal place)
paintTime.setText(String.valueOf(p));
String paintTime = String.valueOf(p);
laborCost.setText(String.valueOf(labCost));
String laborCost = Double.toString(labCost);
} catch (NumberFormatException f)
{
wallHeight.requestFocus();
wallHeight.selectAll();
}
}
}
class ClearBTNListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// clear text fields and set focus
cansNeeded.setText("");
gallonsNeeded.setText("");
wallArea.setText("");
wallHeight.setText("");
wallWidth.setText("");
paintTime.setText("");
sColor.setText("");
laborCost.setText("");
//set focus
wallHeight.requestFocus();
}
}
class ChoiceAListener implements ActionListener
{
public void actionPreformed (ActionEvent e)
{
}
public static void main(String[] args)
{
PaintEstimator window = new PaintEstimator();
window.setVisible(true);
}
}
</code></pre>
<p>Below is the combo box I was able to create:</p>
<pre><code>public static void main(String[] args)
{
String[] optionsToChoose =
{
"White", "Cream", "Sage", "Light Blue", "Eggshell White"
};
JFrame jFrame = new JFrame();
JComboBox<String> jComboBox = new JComboBox<>(optionsToChoose);
jComboBox.setBounds(80, 50, 140, 20);
JButton jButton = new JButton("Done");
jButton.setBounds(100, 100, 90, 20);
JLabel jLabel = new JLabel();
jLabel.setBounds(90, 100, 400, 100);
jFrame.add(jButton);
jFrame.add(jComboBox);
jFrame.add(jLabel);
jFrame.setLayout(null);
jFrame.setSize(350, 250);
jFrame.setVisible(true);
jButton.addActionListener((ActionEvent e) ->
{
String selectedColor = "You selected " +
jComboBox.getItemAt(jComboBox.getSelectedIndex());
jLabel.setText(selectedColor);
});
}
</code></pre>
| 3 | 3,000 |
decompression error while putting together parts with macHacha
|
<p>OK I have app for iPad that reads magazines. All previous issues works fine. I manage to make new issue (before it was done by other guy that left the firm) and to run it in simulator and on device without problems.</p>
<p>Now I add row for new issue of magazine in database and compress all pictures and multimedia by ZIP tool and divide them by MacHacha (because Java class that uploads demand parts from MacHacha to upload one by one) and upload it on server. In App store I downloaded magazine and can see new issue. On server new row is good have all good parameters and the size is adequate to size on disk. </p>
<p>When new issue finnish download it shows me error. I tried same procedure from simulator and in OUTPUT in the moment it crashes shows me decompression error (0).</p>
<p>I supposed that problem is with putting parts together with MacHacha. Can anyone help or give me that catch that solves this problem.</p>
<p>if it will help I can upload new issue and provide link (it's free) I it will be helpful for You guys and girls :)</p>
<p><a href="http://www.mazzantieditori.it/applicazioni/219-nycit-italian-american-magazine.html" rel="nofollow">http://www.mazzantieditori.it/applicazioni/219-nycit-italian-american-magazine.html</a></p>
<p>link for application. In library there is few issues and the last one is new (Giugno 2011).</p>
<p>I will provide code for that method that gives me string for mistake:</p>
<pre><code>- (void)connectionDidFinishLoading:(NSURLConnection *)connection
</code></pre>
<p>{<br>
// controllo se il receipt è corretto e faccio partire il download
if(min == 0 && [receivedData length]
<pre><code>NSString *file = [[self documentsDir:1] stringByAppendingPathComponent:@"archivio.zip"];
if (max <= num && !cancelDownload) {
self.progressBar.progress = (1.0f/num)*min;
min = max+1;
max += 5;
// creo directory per l'elemento scaricato
BOOL isDir = NO;
if(![[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDir]) {
NSError *error;
//creo directory
[[NSFileManager defaultManager] createDirectoryAtPath:[self documentsDir:1] withIntermediateDirectories:YES attributes:nil error:&error];
//creo file vuoto
[[NSFileManager defaultManager] createFileAtPath:file contents:nil attributes:nil];
}
NSFileHandle *handler = [NSFileHandle fileHandleForWritingAtPath:file];
if(handler) {
[handler seekToEndOfFile];
[handler writeData:receivedData];
}
NSLog(@"Received %d bytes of data; min: %i max: %i",[receivedData length],min,max);
[receivedData setLength:0];
// questa è la seconda invocazione
[self downloadArchivePart:@"verified"];
[connection release];
return;
}
NSFileManager *man = [[NSFileManager alloc] init];
NSDictionary *attrs = [man attributesOfItemAtPath:file error: NULL];
//UInt32 result =
NSNumber *size = [attrs objectForKey:NSFileSize];
//int length = [receivedData length];
NSLog(@"Succeeded! Received %i bytes of data",[size intValue]);
[man release];
//1.038.090 è il numero di byte della parte più piccola dell'archivio
if([size intValue] >= kMinPartSize) {
NSLog(@"prod %@",self.prodName);
if(self.prodName == nil || [self.prodName isEqualToString:@""]) self.prodName = prodId;
NSError *error;
BOOL ok = [TWZipArchive unzipFileAtPath:file toDestination:[self documentsDir:1] overwrite:YES password:nil error:&error];
//unzipFileAtPath:file toDestination:[self documentsDir]];
NSString *msg;
if(ok) {
NSLog(@"decompression successfull");
self.progressBar.progress = 1.0f;
NSFileManager *fm = [NSFileManager defaultManager];
[fm removeItemAtPath:file error:&error];
msg = @"Download completed: new issue added in libray";
NSMutableArray *array;
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString *path = [[self documentsDir:0] stringByAppendingPathComponent:@"downloaded.plist"];
if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {
[dict setObject:prodId forKey:@"id"];
[dict setObject:prodName forKey:@"titolo"];
array = [NSArray arrayWithObject:dict];
[array writeToFile:path atomically:YES];
}
array = [NSMutableArray arrayWithContentsOfFile:path];
BOOL exist = NO;
for (int i=0; i<[array count]; i++) {
if ([[[array objectAtIndex:i] objectForKey:@"id"] isEqualToString:prodId]) {
exist = YES;
//prodId = [NSString stringWithFormat:@"%@%i",prodId,i];
}
}
if(exist == NO) {
[dict setObject:prodId forKey:@"id"];
[dict setObject:prodName forKey:@"titolo"];
[array insertObject:dict atIndex:0]; //sempre in testa l'ultimo elemento scaricato
[array writeToFile:path atomically:YES];
}
}
else {
NSLog(@"decompression error");
msg = @"An error has occurred";
}
//[myAlert release];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"NYC.IT"
message:@"Download completed: new issue added in libray"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
//[alert release];
}else {
if(cancelDownload == YES) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"NYC.IT"
message:@"Download stopped for user action"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
}else {
NSString *errFile = [[self documentsDir:1] stringByAppendingPathComponent:@"errFile.html"];
[receivedData writeToFile:errFile atomically:YES];
NSLog(@"err : %@",errFile);
NSLog(@"scrittura error file eseguita");
NSLog(@"receipt non valido");
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"NYC.IT"
message:@"Downloading error: please retry later!"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
}
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
progressBar.hidden = YES;
// release the connection, and the data object
[connection release];
//[receivedData release];
</code></pre>
<p>}</p>
<p>Thanks in Advance...</p>
| 3 | 3,015 |
Merging multiple csvs the right way in panda
|
<p>I have been trying to work out how to combine several (variable amount of) csvs that all contain one same column and column data in Python. I have been looking at panda and have had only a limited success using merge, join or concat. My closest attempt was with concat (see code below). This brought together all the data but added the common field each time.</p>
<p>So I would have for example:</p>
<p>csv1</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Food</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Fruit</td>
</tr>
<tr>
<td>Brocolli</td>
<td>Veg</td>
</tr>
<tr>
<td>Milk</td>
<td>Drink</td>
</tr>
</tbody>
</table>
</div>
<p>csv2</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Food</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>UK</td>
</tr>
<tr>
<td>Brocolli</td>
<td>Spain</td>
</tr>
<tr>
<td>Milk</td>
<td>US</td>
</tr>
</tbody>
</table>
</div>
<p>Desired result csv:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Food</th>
<th>Type</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Fruit</td>
<td>UK</td>
</tr>
<tr>
<td>Brocolli</td>
<td>Veg</td>
<td>Spain</td>
</tr>
<tr>
<td>Milk</td>
<td>Drink</td>
<td>US</td>
</tr>
</tbody>
</table>
</div>
<p>Current result (with code below):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Food</th>
<th>Type</th>
<th>Food</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Fruit</td>
<td>Apple</td>
<td>UK</td>
</tr>
<tr>
<td>Brocolli</td>
<td>Veg</td>
<td>Brocolli</td>
<td>Spain</td>
</tr>
<tr>
<td>Milk</td>
<td>Drink</td>
<td>Milk</td>
<td>US</td>
</tr>
</tbody>
</table>
</div>
<p>Can anyone help please?</p>
<p>Thanks in advance</p>
<pre><code>import glob
import pandas as pd
curdir = os.getcwd()
all_files = glob.glob(os.path.join(curdir, "*37604.csv"))
df_from_each_file = (pd.read_csv(csvfiles) for csvfiles in all_files)
df_merged = pd.concat(df_from_each_file, axis=1, ignore_index=False)
df_merged.to_csv("merged_37604.csv", index=False)```
</code></pre>
| 3 | 1,034 |
Running a Selenium webscraper in AWS Lambda using Docker
|
<p>I am trying to create a simple python Lambda app using SAM CLI that gets the number of followers for a particular handle. Have looked at ALL tutorials and blog posts and yet have not been able to make it work.</p>
<p>The build and local test works fine using <code>sam build</code> and <code>sam local invoke</code>, however, after deployment to AWS Lambda it throws the following error.</p>
<p>Any ideas how to solve this?</p>
<pre><code>{
"errorMessage": "Message: unknown error: Chrome failed to start: crashed.\n (chrome not reachable)\n (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)\n",
"errorType": "WebDriverException",
"stackTrace": [
" File \"/var/task/app.py\", line 112, in main\n data = Twitter(StockInfo_list)\n",
" File \"/var/task/app.py\", line 36, in Twitter\n driver = webdriver.Chrome(executable_path=chromedriver_path, options=chrome_optionsdata)\n",
" File \"/var/task/selenium/webdriver/chrome/webdriver.py\", line 76, in __init__\n RemoteWebDriver.__init__(\n",
" File \"/var/task/selenium/webdriver/remote/webdriver.py\", line 157, in __init__\n self.start_session(capabilities, browser_profile)\n",
" File \"/var/task/selenium/webdriver/remote/webdriver.py\", line 252, in start_session\n response = self.execute(Command.NEW_SESSION, parameters)\n",
" File \"/var/task/selenium/webdriver/remote/webdriver.py\", line 321, in execute\n self.error_handler.check_response(response)\n",
" File \"/var/task/selenium/webdriver/remote/errorhandler.py\", line 242, in check_response\n raise exception_class(message, screen, stacktrace)\n"
]
}
</code></pre>
<p>I'm using the following as my Dockerfile</p>
<pre><code>FROM public.ecr.aws/lambda/python:3.8
# Update repository and install unzip
RUN yum update -y
RUN yum install unzip -y
# Download and install Google Chrome
COPY curl https://intoli.com/install-google-chrome.sh | bash
# Download and install ChromeDriver
RUN CHROME_DRIVER_VERSION=`curl -sS https://chromedriver.storage.googleapis.com/LATEST_RELEASE` && \
wget -O /tmp/chromedriver.zip https://chromedriver.storage.googleapis.com/$CHROME_DRIVER_VERSION/chromedriver_linux64.zip && \
unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/
RUN echo $(chromedriver --version)
# Upgrade PIP
RUN /var/lang/bin/python3.8 -m pip install --upgrade pip
# Install requirements (including selenium)
COPY app.py requirements.txt ./
RUN python3.8 -m pip install -r requirements.txt -t .
# Command can be overwritten by providing a different command in the template directly.
CMD ["app.main"]
</code></pre>
<p>My applications looks like</p>
<pre class="lang-py prettyprint-override"><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import os
import time, datetime
import pandas as pd
import csv
# import mysql.connector
from datetime import date, datetime as dt1
def Twitter(twitter_stock_id):
twitterlist = []
stockids = []
twitterlist = twitter_stock_id["TwitterUrl"].str.lower().tolist()
stockids = twitter_stock_id["stockid"].str.lower().tolist()
chrome_optionsdata = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_optionsdata.add_experimental_option("prefs", prefs)
chrome_optionsdata.add_argument("--headless")
chrome_optionsdata.add_argument("--no-sandbox")
chrome_optionsdata.add_argument("--disable-dev-shm-usage")
chrome_optionsdata.add_argument("--disable-gpu")
chrome_optionsdata.add_argument("--disable-gpu-sandbox")
chromedriver_path = "/usr/local/bin/chromedriver"
driver = webdriver.Chrome(executable_path=chromedriver_path, options=chrome_optionsdata)
lfollowers = []
for url in twitterlist:
tempurl = driver.get(url)
time.sleep(10)
followers = driver.find_elements_by_class_name("r-qvutc0")
for fol in followers:
if "Followers" in fol.text:
tempstr = fol.text.split(" ")
lfollowers.append(tempstr[0])
time.sleep(5)
lmaindata = []
for fld in lfollowers:
if fld != "Followers":
lmaindata.append(fld)
print("Followers" + str(lmaindata))
driver.quit()
return f"Followers: {lmaindata}"
import json
def main(event, context):
StockInfo_list = pd.DataFrame([{"TwitterUrl": "https://twitter.com/costco", "stockid": "COST"}])
data = Twitter(StockInfo_list)
return {
"statusCode": 200,
"body": json.dumps({"message": "hello", "data": data}),
}
</code></pre>
| 3 | 2,073 |
Why base64 image in SVG cannot be shown in Adobe Illustrator?
|
<p>I created an SVG: a grey rectangle filled with <code><pattern></code>. The icons in the pattern are <code><image></code> with base64 svg image. I then saved this svg as a .svg file with my code.</p>
<p>I found the .svg I got can be correctly shown in the browser.
However, when I used Adobe Illustrator to open this .svg, the icons disappeared, only the background grey rectangle can be shown correctly. I also tried another design tool, Figma, which showed the same result as Adobe Illustrator -- only background.
But I can open this .svg correctly in <a href="https://editor.method.ac/" rel="nofollow noreferrer">an online SVG editor</a>.</p>
<p>Do you know why it is like this, or how to download this svg and correctly show it in Adobe Illustrator?</p>
<p>Thank you in advance.</p>
<p>My code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var btn = document.getElementById("btn")
btn.onclick = function(){
console.log("save svg")
var svgData = $("#mySVG")[0].outerHTML;
console.log(svgData);
var svgBlob = new Blob([svgData], {type:"image/svg+xml;charset=utf-8"});
var svgUrl = URL.createObjectURL(svgBlob);
var downloadLink = document.createElement("a");
downloadLink.href = svgUrl;
downloadLink.download = "mySVG.svg";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg id = "mySVG" width="200" height="200" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect width="200" height="200" fill="lightgrey"/>
<rect width="200" height="200" fill="url(#pattern)"/>
<defs>
<pattern id="pattern" patternUnits="userSpaceOnUse" width="40" height="40">
<image x="0" y="0" width="40" height="40" xlink:href="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIHdpZHRoPSI1MHB4IiBoZWlnaHQ9IjUwcHgiIHZpZXdCb3g9IjAgMCA1MCA1MCIgZW5hYmxlLWJhY2tncm91bmQ9Im5ldyAwIDAgNTAgNTAiIHZlcnNpb249IjEuMSIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+PGcgaWQ9IkxheWVyXzIzIi8+PGcgaWQ9IkxheWVyXzIyIi8+PGcgaWQ9IkxheWVyXzIxIi8+PGcgaWQ9IkxheWVyXzIwIi8+PGcgaWQ9IkxheWVyXzE5Ii8+PGcgaWQ9IkxheWVyXzE4Ij48cGF0aCBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zMC4wNzQsMTMuMDg5Yy0xLjA3NC0yLjc3OC00LjgyNy0zLjk0LTcuMzY4LTIuNDc5bC0wLjQ2NSwwLjI2OSAgIGMtMC4yMjEtMy42MDUsMC4wNy02LjkxOCwwLjU2Ny0xMC40OTRMMjAuMDMyLDBjLTAuNDM1LDMuMTMzLTAuNzMzLDYuMTU5LTAuNjU5LDkuMzI0bC00LjUwOS03LjgxTDEyLjQ0LDIuOTA4bDQuNDYxLDcuNzM4ICAgYy0yLjY5MS0xLjY1OC01LjQ0Ni0yLjg3My04LjM5OS0zLjk5N0w3LjUwMyw5LjI3MWMzLjM5NywxLjI5Myw2LjM3NywyLjY2LDkuMzg2LDQuNjk4bC0wLjQ1NiwwLjI2NCAgIGMtMi4zNDMsMS4zMjktMy4zMzIsNC42OTQtMS45NzQsNy4wNDVjMC4zMjksMC41NzEsMC45MjcsMS4xOTgsMS4zNDYsMS42OTFsNS4yMTctMy4wMjZsMS4yMzksMi4xMzlsLTQuODMsMi44MDJsNy41OCw4LjkxOSAgIGw1LjQ1Ni0zLjIwOGwxLjI0OSwyLjEzbC01LjA4MSwyLjk4OEwzOC43NzgsNTBsMy43MTktMi4xMzhjLTMuMTg1LTguMTgzLTUuOTAzLTE2LjQ5Ny04Ljc4NC0yNC43ODNsLTQuODcsMi44NmwtMS4yNDktMi4xMyAgIGw1LjI4Ni0zLjEwNkMzMS45OCwxOC4xNTksMzEuMDUyLDE1LjYyLDMwLjA3NCwxMy4wODkiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48ZyBpZD0iTGF5ZXJfMTciLz48ZyBpZD0iTGF5ZXJfMTYiLz48ZyBpZD0iTGF5ZXJfMTUiLz48ZyBpZD0iTGF5ZXJfMTQiLz48ZyBpZD0iTGF5ZXJfMTMiLz48ZyBpZD0iTGF5ZXJfMTIiLz48ZyBpZD0iTGF5ZXJfMTEiLz48ZyBpZD0iTGF5ZXJfMTAiLz48ZyBpZD0iTGF5ZXJfOSIvPjxnIGlkPSJMYXllcl84Ii8+PGcgaWQ9IkxheWVyXzciLz48ZyBpZD0iTGF5ZXJfNiIvPjxnIGlkPSJMYXllcl81Ii8+PGcgaWQ9IkxheWVyXzQiLz48ZyBpZD0iTGF5ZXJfMyIvPjxnIGlkPSJMYXllcl8yIi8+PC9zdmc+"></image>
</pattern>
</defs>
</svg>
<button id="btn">Save SVG</button></code></pre>
</div>
</div>
</p>
<p>When I open mySVG.svg in the browser, it looks like this. This is what I want.</p>
<p><a href="https://i.stack.imgur.com/HZ9zL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HZ9zL.png" alt="mySVG in the browser" /></a></p>
<p>When I open mySVG.svg in the Adobe Illustrator, the icon images are not shown. We can only see the background.</p>
<p><a href="https://i.stack.imgur.com/IoSKV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IoSKV.png" alt="mySVG in the Adobe Illustrator" /></a></p>
| 3 | 2,501 |
Class not serializable exception when creatin an inner class in java
|
<p>My code is similar to this thread.
<a href="https://stackoverflow.com/questions/6662529/class-not-serializable-after-methods-are-overridden?newreg=89e2c3fc5b4541b6ad23d7a76ae54b62">Class not serializable after methods are overridden</a></p>
<p>But my goal is to send a method to be processed on another computer.
So, i created this class which exists on both ends. When i'm about to serialize the class, i override the method just as shown in above thread, i get the non serializable exception.
I saw in the above thread that i must create a static inner class. How can i do this?! An anonymus inner class cant be static!
And if i explicit the class name, i'll have a problem on the de-serialization end of the application.</p>
<p>Client Code:</p>
<pre><code>public static void main(String[] args) {
try {
// TODO code application logic here
Socket client = new Socket("192.168.25.22", 62222);
System.out.println("Cliente conectado");
ObjectInputStream input = new ObjectInputStream(client.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
try {
Task t =(Task) input.readUnshared();
System.out.println("Objeto recebido...");
t.myTask();
System.out.println("ok");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
} catch (Exception ex) {
System.out.println("ERRO!");
ex.printStackTrace();
}
}
</code></pre>
<p>Server Code:</p>
<pre><code>public static void main(String args[]) {
try {
ServerSocket server = new ServerSocket(62222);
System.out.println("Listening on 62222...");
Socket client = server.accept();
System.out.println("New client connected with IP: " + client.getInetAddress().getHostAddress());
Task t = new Task(null){@Override public void myTask(){System.out.println("Olá");}};
//Task tz = new Tsk(null);
ObjectOutputStream output;
output = new ObjectOutputStream(client.getOutputStream());
output.writeUnshared(t);
output.close();
System.out.println("Task created");
System.out.println("Objeto enviado.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
</code></pre>
<p>Task Class Code:</p>
<pre><code> public class Task implements Serializable{
List<Object> dataImput;
List<Object> dataOutput;
boolean finished;
private static final long serialVersionUID = 595012310163575L;
public Task(List<Object> dataImput){
this.finished=false;
this.dataImput= dataImput;
}
public void myTask(){
System.out.println("Not Implemented.");
}
public boolean isFinished() {
return finished;
}
</code></pre>
<p>}</p>
| 3 | 1,191 |
How to pass state from parent to child as props then from that child to it s child as props in React.js
|
<p>For now everything is static data .</p>
<p><strong>I have a parent sate: an array containing 4 objects
like so :</strong></p>
<pre><code> function App(){
const [searchResults,setSearchResults] =
useState([
{
name: 'name1',
artist: 'artist1',
album: 'album1',
id: 1
},
{
name: 'name2',
artist: 'artist2',
album: 'album2',
id: 2
},
{
name: 'name3',
artist: 'artist3',
album: 'album3',
id: 3
},
{
name: 'name4',
artist: 'artist4',
album: 'album4',
id: 4
}
]);
</code></pre>
<p><strong>i pass this state to the child in the return with this it works as expected :</strong></p>
<pre><code>return (
<SearchResults searchResults = {searchResults} />
)
</code></pre>
<p><strong>and from i pass it to :</strong></p>
<pre><code>import React,{useEffect,useState} from "react";
import './SearchResults.css';
import TrackList from '../TrackList/TrackList';
export default function SearchResults({searchResults}) {
return (
<div className="SearchResults">
<h2>Results</h2>
<TrackList tracks = {searchResults} />
</div>
)
}
</code></pre>
<p>now is where things got me confused.</p>
<p><strong>i try to map the data from the array to the child of this component like this(this is the whole component) :</strong></p>
<pre><code>import React,{useEffect,useState} from "react";
import './TrackList.css';
import Track from '../Track/Track'
export default function TrackList(props) {
return(
<div className="TrackList">
{
props.tracks.map( track => {
<Track track = {track} key = {track.id} />
})
}
</div>
)
}
</code></pre>
<p><strong>and i get this error with the local server displaying a white screen</strong>
[1]: <a href="https://i.stack.imgur.com/5niRQ.png" rel="nofollow noreferrer">https://i.stack.imgur.com/5niRQ.png</a></p>
<ul>
<li>i tried destructuring and assigning props value to a variable before mapping but didn't work .</li>
<li>also when i remove the .map i can see that has a props with expected data in it using react dev tools .</li>
</ul>
| 3 | 1,024 |
Asterisk - macro GotoIf or operator
|
<pre><code>Asterisk 16.13.0
</code></pre>
<p>Want to switch action between (primo, secondo, terzo and bo) based on the caller number.</p>
<pre><code>[macro-gigi]
exten => s,1,NoOp(macro-gigi: ${CALLERID(num)} - ${CALLERID(all)} - ${CHANNEL})
exten => s,n,GotoIf($["${CALLERID(num)}"="207"]?primo)
exten => s,n,GotoIf($["${CALLERID(num)}"="205"|"206"]?secondo:terzo)
exten => s,n(bo),NoOp(caller not managed: ${CALLERID(num)} - ${EXTEN} - ${CALLERID(all)} - ${CHANNEL})
exten => s,n,MacroExit
exten => s,n(primo),NoOp(primo: ${CALLERID(num)} - ${CALLERID(all)} - ${CHANNEL})
exten => s,n,MacroExit
exten => s,n(secondo),NoOp(secondo: ${CALLERID(num)} - ${CALLERID(all)} - ${CHANNEL})
exten => s,n,MacroExit
exten => s,n(terzo),NoOp(terzo: ${CALLERID(num)} - ${CALLERID(all)} - ${CHANNEL})
exten => s,n,GotoIf($["${CALLERID(num)}"="203"|"204"]?:bo)
exten => s,n,NoOp(terzo: ${CALLERID(num)} - ${CALLERID(all)} - ${CHANNEL})
exten => s,n,MacroExit
</code></pre>
<p>If the caller is 207 it run primo and this is fine.</p>
<p>If the caller is 203 or 204 it run secondo and this is wrong.</p>
<p>If the caller is 206 or 205 it run secondo and this is fine.</p>
<p>If the caller is someone else it run secondo and this is wrong.</p>
<p>I don't get if it is wrong the use of OR opeator <code>="205"|"206"</code> or the gotoif sequences.</p>
<pre><code>-- Executing [s@macro-gigi:1] NoOp("SIP/206-00000042", "macro-gigi: 206 - SIP/206-00000042") in new stack
-- Executing [s@macro-gigi:2] GotoIf("SIP/206-00000042", "0?primo") in new stack
-- Executing [s@macro-gigi:3] GotoIf("SIP/206-00000042", ""206"?secondo:terzo") in new stack
-- Goto (macro-gigi,s,8)
-- Executing [s@macro-gigi:8] NoOp("SIP/206-00000042", "secondo: 206 - SIP/206-00000042") in new stack
-- Executing [s@macro-gigi:9] MacroExit("SIP/206-00000042", "") in new stack
-- Executing [s@macro-gigi:1] NoOp("SIP/203-00000044", "macro-gigi: 203 - SIP/203-00000044") in new stack
-- Executing [s@macro-gigi:2] GotoIf("SIP/203-00000044", "0?primo") in new stack
-- Executing [s@macro-gigi:3] GotoIf("SIP/203-00000044", ""206"?secondo:terzo") in new stack
-- Goto (macro-gigi,s,8)
-- Executing [s@macro-gigi:8] NoOp("SIP/203-00000044", "secondo: 203 - SIP/203-00000044") in new stack
-- Executing [s@macro-gigi:9] MacroExit("SIP/203-00000044", "") in new stack
-- Executing [s@macro-gigi:1] NoOp("SIP/204-00000045", "macro-gigi: 204 - SIP/204-00000045") in new stack
-- Executing [s@macro-gigi:2] GotoIf("SIP/204-00000045", "0?primo") in new stack
-- Executing [s@macro-gigi:3] GotoIf("SIP/204-00000045", ""206"?secondo:terzo") in new stack
-- Goto (macro-gigi,s,8)
-- Executing [s@macro-gigi:8] NoOp("SIP/204-00000045", "secondo: 204 - SIP/204-00000045") in new stack
-- Executing [s@macro-gigi:9] MacroExit("SIP/204-00000045", "") in new stack
-- Executing [s@macro-gigi:1] NoOp("SIP/205-00000043", "macro-gigi: 205 - SIP/205-00000043") in new stack
-- Executing [s@macro-gigi:2] GotoIf("SIP/205-00000043", "0?primo") in new stack
-- Executing [s@macro-gigi:3] GotoIf("SIP/205-00000043", "1?secondo:terzo") in new stack
-- Goto (macro-gigi,s,8)
-- Executing [s@macro-gigi:8] NoOp("SIP/205-00000043", "secondo: 205 - SIP/205-00000043") in new stack
-- Executing [s@macro-gigi:9] MacroExit("SIP/205-00000043", "") in new stack
-- Executing [s@macro-gigi:1] NoOp("PJSIP/102-00000050", "macro-gigi: 102 - PJSIP/102-00000050") in new stack
-- Executing [s@macro-gigi:2] GotoIf("PJSIP/102-00000050", "0?primo") in new stack
-- Executing [s@macro-gigi:3] GotoIf("PJSIP/102-00000050", ""206"?secondo:terzo") in new stack
-- Goto (macro-gigi,s,8)
-- Executing [s@macro-gigi:8] NoOp("PJSIP/102-00000050", "secondo: 102 - PJSIP/102-00000050") in new stack
-- Executing [s@macro-gigi:9] MacroExit("PJSIP/102-00000050", "") in new stack
</code></pre>
<p><strong>EDIT:</strong></p>
<p>With this change it works everything but it isn't DRY:</p>
<pre><code>exten => s,1,NoOp(macro-gigi: ${CALLERID(num)} - ${CHANNEL})
exten => s,n,GotoIf($["${CALLERID(num)}"="205"]?secondo)
exten => s,n,GotoIf($["${CALLERID(num)}"="206"]?secondo)
exten => s,n,GotoIf($["${CALLERID(num)}"="207"]?primo)
exten => s,n,GotoIf($["${CALLERID(num)}"="203"]?terzo)
exten => s,n,GotoIf($["${CALLERID(num)}"="204"]]?terzo:bo)
</code></pre>
| 3 | 2,469 |
Causedby:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter' on a null object reference
|
<h1>DisplayActivity.java</h1>
<p>I'm relatively new to android.I am trying to make a list view that contains music.The app is perfectly build but then when i try to run it on the device it crashes.I try to debug the app and it gave me the above error.Here are my following code</p>
<pre><code>package com.bytetex.azmusic;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.File;
import java.util.ArrayList;
public class DisplayActivity extends AppCompatActivity {
private String[] itemsAll;
private ListView mSongsLists;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
appExternalStorageStoragePermission();
mSongsLists=findViewById(R.id.songLists);
}
public void appExternalStorageStoragePermission() {
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
dispalyAudioSongName();
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> readOnluAudioSongs(File file) {
ArrayList<File> arrayList = new ArrayList<>();
File[] allFiles = file.listFiles();
assert allFiles != null;
for (File individualFile : allFiles) {
if (individualFile.isDirectory() && !individualFile.isHidden()) {
arrayList.addAll(readOnluAudioSongs(individualFile));
} else {
if (individualFile.getName().endsWith(".mp3") || individualFile.getName().endsWith(".aac") || individualFile.getName().endsWith(".wav") || individualFile.getName().endsWith(".wma")) {
{
arrayList.add(individualFile);
}
}
}
}
return arrayList;
}
private void dispalyAudioSongName()
{
final ArrayList<File> audioSong= readOnluAudioSongs(Environment.getExternalStorageDirectory());
itemsAll=new String[audioSong.size()];
for (int songCounter=0; songCounter<audioSong.size(); songCounter++)
{
itemsAll[songCounter]=audioSong.get(songCounter).getName();
}
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(DisplayActivity.this, android.R.layout.simple_list_item_1, itemsAll);
mSongsLists.setAdapter(arrayAdapter);
}
}
</code></pre>
<h1>activity_display.xml</h1>
<p>here is my xml code</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".DisplayActivity">
<ListView
android:id="@+id/songLists"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
</code></pre>
| 3 | 1,873 |
Microsoft.Azure.Mobile Client - Handling Server Error using custom IMobileServiceSyncHandler - Xamarin Forms
|
<p>I have implemented the Azure - Offline Sync based on the documentation / Sample provided by Microsoft <a href="https://github.com/Azure/azure-mobile-apps-quickstarts/blob/master/client/xamarin.forms/ZUMOAPPNAME/TodoItemManager.cs" rel="nofollow noreferrer">Sample</a> in my Xamarin Forms Application.</p>
<p>In the sample / documentation provided, they are using the default Service Handler.</p>
<p><strong>// Simple error/conflict handling. A real application would handle the various errors like network conditions,server conflicts and others via the IMobileServiceSyncHandler.</strong> </p>
<p>Since I need to implement a <strong>retry logic for 3 times</strong> if the <strong>Pull / Push fails.</strong> As per the documentation I have created a custom Service Handler(<strong>IMobileServiceSyncHandler</strong>).</p>
<p><strong>Please find my code logic here.</strong></p>
<pre><code>public class CustomSyncHandler : IMobileServiceSyncHandler
{
public async Task<JObject> ExecuteTableOperationAsync(IMobileServiceTableOperation operation)
{
MobileServiceInvalidOperationException error = null;
Func<Task<JObject>> tryExecuteAsync = operation.ExecuteAsync;
int retryCount = 3;
for (int i = 0; i < retryCount; i++)
{
try
{
error = null;
var result = await tryExecuteAsync();
return result;
}
catch (MobileServiceConflictException e)
{
error = e;
}
catch (MobileServicePreconditionFailedException e)
{
error = e;
}
catch (MobileServiceInvalidOperationException e)
{
error = e;
}
catch (Exception e)
{
throw e;
}
if (error != null)
{
if(retryCount <=3) continue;
else
{
//Need to implement
//Update failed, reverting to server's copy.
}
}
}
return null;
}
public Task OnPushCompleteAsync(MobileServicePushCompletionResult result)
{
return Task.FromResult(0);
}
}
</code></pre>
<p>But I am not sure how to handle / revert <strong>server copy in case all the 3 retry failed.</strong></p>
<p>In the TODO sample they where <strong>reverting</strong> it based on the
<strong>MobileServicePushFailedException</strong>. But which is available when we implement <strong>IMobileServiceSyncHandler</strong>.
More over if we include custom IMobileServiceSyncHandler it wont execute the code after <strong>PushAsync / PullAsync</strong>. Even the try catch wont fire in case any exception.</p>
<pre><code> try
{
await this.client.SyncContext.PushAsync();
await this.todoTable.PullAsync(
//The first parameter is a query name that is used internally by the client SDK to implement incremental sync.
//Use a different query name for each unique query in your program
"allTodoItems",
this.todoTable.CreateQuery());
}
catch (MobileServicePushFailedException exc)
{
if (exc.PushResult != null)
{
syncErrors = exc.PushResult.Errors;
}
}
// Simple error/conflict handling. A real application would handle the various errors like network conditions,
// server conflicts and others via the IMobileServiceSyncHandler.
if (syncErrors != null)
{
foreach (var error in syncErrors)
{
if (error.OperationKind == MobileServiceTableOperationKind.Update && error.Result != null)
{
//Update failed, reverting to server's copy.
await error.CancelAndUpdateItemAsync(error.Result);
}
else
{
// Discard local change.
await error.CancelAndDiscardItemAsync();
}
Debug.WriteLine(@"Error executing sync operation. Item: {0} ({1}). Operation discarded.", error.TableName, error.Item["id"]);
}
}
}
</code></pre>
<p><strong>Note</strong></p>
<p>In my application I am only trying to achieve retry for 3 time in case any server error. I am not looking for to resolve conflicts. Thant is the reason I haven't added the code for the same.</p>
<p>If someone came across similar issues and resolved it please help.</p>
<p>Stez.</p>
| 3 | 2,017 |
How can i change color in a table when i changes values in the table? I get the values from db with json
|
<p>When I click on the <code>checkbox</code> and the value of that row changes or when i add a new workout and the table changes i want it to change color... I don't know how to proceed. </p>
<p>Please help me :)</p>
<p>I think it could be something like this: <code>$('#TblWorkouts input').on('change'</code> but I'm don't know. </p>
<p>Jag har en uppgift att lämna in där ett krav är att när en rad i tabellen ändras ska den få en annan färg men jag vet inte hur jag ska gå till väga.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<script>
*$('#TblWorkouts input').on('change' <!--- how to make the table row change color when a value has been changed or a new row have been added? -->*
function getAllWorkouts() {
$.getJSON("./index1.php/controller/getWorkouts", function (jsondata){
showWorkoutsInTable(jsondata);
});
}
function addWork() {
let workoutet=$("#textWork").val();
// var checkedValue = $('.messageCheckbox:checked').val();
let donet=$("#CheckDone:checked").val();
alert(donet);
$.post("./index1.php/controller/addWorkout",{workout:workoutet, done:donet}, function (jsondata) {
alert(jsondata['klar']);
})
getAllWorkouts();
}
function updateWorkout() {
let idt=$("#txtId").val();
let donet=$("#done:checked").val();
$.post("./index1.php/controller/updateWorkout",{id:idt, done:donet}, function (jsondata) {
alert(jsondata['svar']);
});
}
function showWorkoutsInTable(jsondata) {
let table=$("#TblWorkouts");
table.empty();
$.each(jsondata, function(idx, workout){
table.append("<tr>");
table.append("<td>"+workout['id']+" </td>");
table.append("<td>"+workout['workout']+" </td>");
table.append("<td>"+workout['date']+" </td>");
if(workout['done']==1){
table.append("<td> <input onclick='updateWorkout()' type=\"checkbox\" checked value='1' id=\"done\">Ja</input></td>");
}
else{
table.append("<td> <input onclick='updateWorkout()' type=\"checkbox\" value='1' id=\"done\">Ja</input></td>");
}
table.append("<td>"+workout['done']+"</td>");
table.append("</tr>");
})
}
$(document).ready(function(){
getAllWorkouts();
});
</script>
</head>
<body>
<div>
<h1>Tittis träning</h1>
</div>
<addForm style="width:25%" >
<label> Träning: </label>
<input type="text" class="form-control" id="textWork" required>
<label for="checkDone">Utförd: </label>
<input type="checkbox" id="CheckDone" value="1" >Ja</input>
<button onclick="addWork()" class="btn btn-primary">Lägg till</button>
</addForm>
<br>
<table class="table" id="TblWorkouts" style="max-width: 50%">
</table>
</body>
</html></code></pre>
</div>
</div>
</p>
| 3 | 1,848 |
getting blackscreen between activities using a timer
|
<p>i have read multiple links and tried various things yet i can not get the black screen to dissapear any suggestions here is my manifest the activity that is calling the next activity and xmls,code</p>
<p>its basically a splash screen that after 5 seconds it opens another activity it was working two days ago and last night i fixed a logical error then this started tried reverting it to the way it was before i edited it and yet still a black screen after the splash has been displayed.</p>
<p>manifest</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.audiovolumecontrol"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Splash"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.audiovolumecontrol.Options"
android:label="@string/options_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="VolumeControlMAIN"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name=".com.example.audiovolumecontrol.VolumeControlMAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<p>splash xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/splash_main2"
android:orientation="vertical"
>
</LinearLayout>
</code></pre>
<p>Splash Code</p>
<pre><code>package com.example.audiovolumecontrol;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class Splash extends Activity
{
private static int LOGO_TIME_OUT = 5000;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
}
@Override
protected void onStart()
{
// TODO Auto-generated method stub
super.onStart();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent openSTART = new Intent
(Splash.this,VolumeControlMAIN.class);
startActivity(openSTART);
}
}, LOGO_TIME_OUT );
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
</code></pre>
<p>help would be appreciated </p>
<p>I have tried multiple suggestions and noneof them worked from changing the theme to the on start methods and changing variables .... this program worked previously and now once my splash has shown and the time is up i just get a black screen</p>
| 3 | 1,503 |
Python and Webkit, watching serial port thread, how to avoid core dump running javascript
|
<p>I'm writing a game that uses python and webkit, and a webpage is the front-end/GUI. The PC is connected to an Arduino that controls a coin hopper and other i/o. When the Arduino sends 'coinin' over serial, I capture this in a serial-watching thread, then run some javascript on the webpage to 'add' a coin to the game. </p>
<p>For simplicity in troubleshooting, I set up an example that runs a test thread instead of reading serial, but the problem is the same. The thread tries to add a coin every second by running 'addcoin()' on the webpage. If you uncomment the run_javascript() line, the program core dumps. </p>
<p>I came up with a keyboard hack workaround. The test thread, instead of trying to run_javascript() directly, does an os.system call to xdotool to type the letters 'conn' to the program window. That window has a key-event listener, and when it gets the letters 'conn' in keybuffer[], it then runs the desired run_javascript() call to the webpage. If you copy the two files to a folder, and run the python program, you'll see the coin text count up every second (Hit BackSpace to end the program). If you try to run the javascript from the thread instead, you'll see the program core dump.</p>
<p>The question is, is there a better way to do this, without having to use the keyboard hack to run the javascript? Although the hack gets around the problem, it introduces a weakness in the game. You can cheat a coin in by typing 'conn' on the keyboard. I'd like to find some other way to trigger the event, without having to use the keyboard event.</p>
<p><strong>Sample webpage index.htm</strong></p>
<pre><code><html>
<script language="JavaScript" type="text/javascript">
var mycoins=0;
document.onkeydown = function(evt) {
evt = evt || window.event;
cancelKeypress = (evt.ctrlKey && evt.keyCode == 84);
return false;
};
function addcoin()
{
mycoins+=1;
id('mycoins').innerHTML="You Have "+mycoins.toString()+" coins"
}
function id(myID){return document.getElementById(myID)}
</script>
<html>
<body>
<div id=mycoins>You Have 0 Coins</div>
</body>
</html>
</code></pre>
<p><strong>sample python</strong></p>
<pre><code>#!/usr/bin/python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
gi.require_version('WebKit2', '4.0')
from gi.repository import WebKit2
import os,time,sys,threading,serial
defaultpath = os.path.dirname(os.path.realpath(__file__))
killthread=False
keybuffer=[]
buffkeys=['c','o','n','h','p','e']
myname=os.path.basename(__file__)
serial_ports=['/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyACM0','/dev/ttyACM1']
checkserial=True;
class BrowserView:
def __init__(self):
global checkserial
window = Gtk.Window()
window.connect("key-press-event", self._key_pressed, window)
self.view = WebKit2.WebView()
self.view.load_uri('file:///'+defaultpath+'/index.htm')
self.view.connect("notify::title", self.window_title_change)
window.add(self.view)
window.fullscreen()
window.show_all()
'''
######not used for this example#######################################
serial_port=""
for x in serial_ports:
#print 'trying ',x
if os.popen('ls '+x+' >/dev/null 2>&1 ; echo $?').read().strip()=='0':
serial_port=x
break;
baud=9600
if len(serial_port)>1:
self.ser = serial.Serial(serial_port, baud, timeout=0)
else:
self.view.load_uri('file:///'+defaultpath+'/signDOWN.htm?Serial%20Port%20Error|Keno%20will%20auto%20close')
checkserial=False;
if checkserial:
thread = threading.Thread(target=self.read_from_port)
thread.start()
#######################################################################
'''
#####thread test#############
thread = threading.Thread(target=self.testthread)
thread.start()
def testthread(self):
while True:
os.system('xdotool search --name '+myname+' type conn')
#self.view.run_javascript('addcoin()') #causes core dump
if killthread==True:
break;
time.sleep(1)
def read_from_port(self):
while True:
if self.ser.inWaiting()>0:
response=self.ser.readline()
print(response)
if 'coinin' in response:
os.system('xdotool search --name '+myname+' type conn')
#self.view.run_javascript('addcoin()') #causes core dump
if killthread==True:
break;
time.sleep(1)
def checkbuffer(self):
global keybuffer
if 'conn' in ''.join(str(x) for x in keybuffer):
self.view.run_javascript('addcoin()')
keybuffer=[]
def window_title_change(self, widget, param):
if not self.view.get_title():
return
os.chdir(defaultpath)
if self.view.get_title().startswith("pythondiag:::"):
message = self.view.get_title().split(":::",1)[1]
os.system('zenity --notification --text='+message+' --timeout=2')
def _key_pressed(self, widget, event, window):
global keybuffer
mykey=Gdk.keyval_name(event.keyval)
isakey=False
for x in buffkeys:
if mykey==x:
isakey=True;
if isakey:
keybuffer.append(Gdk.keyval_name(event.keyval))
else:
keybuffer=[]
self.checkbuffer()
if mykey == 'BackSpace':
self.myquit()
def myquit(self):
global killthread
killthread=True
try:
self.ser.write('clear\n')
except:
pass
Gtk.main_quit()
if __name__ == "__main__":
BrowserView()
Gtk.main()
</code></pre>
| 3 | 2,473 |
Invalid precision value writing to Oracle wth VBSript
|
<p>Since you all led me in the right direction yesterday, I'm back. I am migrating from windows 2003 to windows 2012. A couple of small, but vital, apps are written in asp (VBScript) and an Oracle 11g DB. Many of the DB calls are failing. The latest is a procedure call. I don't write VBScript so I'm struggling here. The driver is Oracle in OraClient11g_home2</p>
<p>Thanks in advance.</p>
<p>The fields: </p>
<pre><code> 'P_PAX_ID NUMBER(5) IN
'P_YEAR VARCHAR2(4) IN
'P_CARDNUMBER VARCHAR2(16) IN
'P_EXPDATE VARCHAR2(4) IN
'P_PREFIX VARCHAR2(5) IN
'P_FIRST_NAME VARCHAR2(20) IN
'P_LAST_NAME VARCHAR2(20) IN
'P_SUFFIX VARCHAR2(5) IN
'P_ADDRESS VARCHAR2(100) IN
'P_CITY VARCHAR2(30) IN
'P_STATE VARCHAR2(2) IN
'P_ZIP VARCHAR2(9) IN
'P_AMT NUMBER(10,2) IN
'P_STATUS VARCHAR2(10) IN
'P_SOURCE VARCHAR2(1) IN
'P_CC_ID NUMBER(10) OUT
'P_ERR_CD VARCHAR2 OUT
'P_ERR_MSG VARCHAR2 OUT
'P_ACCT_ID VARCHAR2(4) IN DEFAULT
'P_BATCH_ID NUMBER(5) IN DEFAULT
'P_BATCH_ITEM NUMBER(3) IN DEFAULT
'P_BATCH_DT DATE IN DEFAULT
'P_VERISIGN_RESULT NUMBER(10) IN DEFAULT
'P_VERISIGN_PNREF VARCHAR2(12) IN DEFAULT
'P_VERISIGN_RESPMSG VARCHAR2(2000) IN DEFAULT
'P_VERISIGN_CARDSECURE VARCHAR2(1) IN DEFAULT
</code></pre>
<p>The code:</p>
<pre><code>With cmdCCpayment
.CommandText = "{call package.procedure( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )}"
.CommandType = 1 'adCmdText
.ActiveConnection= objConnSessionAuth
'P_PAX_ID
.Parameters(0).Type = 131 'adNumeric
.Parameters(0).Direction = 1 'adParamInput
.Parameters(0).Value = session("pax_id")
'P_YEAR
.Parameters(1).Type = 200 'adVarChar
.Parameters(1).Direction = 1 'adParamInput
.Parameters(1).Value = session("user_year") 'session("user_year")
'P_CARDNUMBER
.Parameters(2).Type = 200 'adVarChar
.Parameters(2).Direction = 1 'adParamInput
.Parameters(2).Value = Session("cc_number")
'P_EXPDATE
.Parameters(3).Type = 200 'adVarChar
.Parameters(3).Direction = 1 'adParamInput
.Parameters(3).Value = Session("cc_exp_month") & Session("cc_exp_year")
'P_PREFIX
.Parameters(4).Type = 200 'adVarChar
.Parameters(4).Direction = 1 'adParamInput
.Parameters(4).Value = Session("cc_prefix")
'P_FIRST_NAME
.Parameters(5).Type = 200 'adVarChar
.Parameters(5).Direction = 1 'adParamInput
.Parameters(5).Value = Session("cc_f_name")
'P_LAST_NAME
.Parameters(6).Type = 200 'adVarChar
.Parameters(6).Direction = 1 'adParamInput
.Parameters(6).Value = Session("cc_l_name")
'P_SUFFIX
.Parameters(7).Type = 200 'adVarChar
.Parameters(7).Direction = 1 'adParamInput
.Parameters(7).Value = Session("cc_suffix")
'P_ADDRESS
.Parameters(8).Type = 200 'adVarChar
.Parameters(8).Direction = 1 'adParamInput
.Parameters(8).Value = Session("cc_address")
'P_CITY
.Parameters(9).Type = 200 'adVarChar
.Parameters(9).Direction = 1 'adParamInput
.Parameters(9).Value = Session("cc_city")
'P_STATE
.Parameters(10).Type = 200 'adVarChar
.Parameters(10).Direction = 1 'adParamInput
.Parameters(10).Value = Session("cc_state")
'P_ZIP
.Parameters(11).Type = 200 'adVarChar
.Parameters(11).Direction = 1 'adParamInput
.Parameters(11).Value = Session("cc_zip")
'P_AMT
.Parameters(12).Type = 131 'adNumeric
.Parameters(12).Direction = 1 'adParamInput
.Parameters(12).Value = Session("cc_amt")
'P_STATUS
.Parameters(13).Type = 200 'adVarChar
.Parameters(13).Direction = 1 'adParamInput
.Parameters(13).Value = "PENDING"
'P_SOURCE
.Parameters(14).Type = 200 'adVarChar
.Parameters(14).Direction = 1 'adParamInput
.Parameters(14).Value = P_SOURCE
'P_CC_ID
.Parameters(15).Type = 131 'adNumeric
.Parameters(15).Direction = 2 'adParamOutput
'P_ERR_CD
.Parameters(16).Type = 200 'adVarChar
.Parameters(16).Direction = 2 'adParamOutput
'P_ERR_MSG
.Parameters(17).Type = 200 'adVarChar
.Parameters(17).Direction = 2 'adParamOutput
End With
I HOPE THIS HELPS. I'm not and asp guy. I'm at my wits end.
Dim objConnSessionAuth
Set objConnSessionAuth = CreateObject("ADODB.Connection")
strConn2 = "DSN=*****;"
strConn2 = strConn2 & "PWD=" & userpassword & ";"
strConn2 = strConn2 & "UID=" & userid & ";"
'strConn2 = strConn2 & "SERVER=" & varEnvironment & ";" 'this is set to dev or prod
'objConnSessionAuth.Provider="MSDASQL.1"
objConnSessionAuth.ConnectionString=strConn2
'objConnSessionAuth.ConnectionString=strConn2
objConnSessionAuth.CursorLocation=3 'adUseClient
'to open this connection call this line
objConnSessionAuth.Open
Dim cmdCCpayment
Set cmdCCpayment = Server.CreateObject("ADODB.Command")
With cmdCCpayment
.CommandText = "{call package.procedure( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )}"
.CommandType = 1 'adCmdText
.ActiveConnection= objConnSessionAuth
'P_PAX_ID
.Parameters(0).Type = 131 'adNumeric
.Parameters(0).Direction = 1 'adParamInput
.Parameters(0).Value = session("pax_id")
'P_YEAR
.Parameters(1).Type = 200 'adVarChar
.Parameters(1).Direction = 1 'adParamInput
.Parameters(1).Value = session("user_year") 'session("user_year")
'P_CARDNUMBER
.Parameters(2).Type = 200 'adVarChar
.Parameters(2).Direction = 1 'adParamInput
.Parameters(2).Value = Session("cc_number")
'P_EXPDATE
.Parameters(3).Type = 200 'adVarChar
.Parameters(3).Direction = 1 'adParamInput
.Parameters(3).Value = Session("cc_exp_month") & Session("cc_exp_year")
'P_PREFIX
.Parameters(4).Type = 200 'adVarChar
.Parameters(4).Direction = 1 'adParamInput
.Parameters(4).Value = Session("cc_prefix")
'P_FIRST_NAME
.Parameters(5).Type = 200 'adVarChar
.Parameters(5).Direction = 1 'adParamInput
.Parameters(5).Value = Session("cc_f_name")
'P_LAST_NAME
.Parameters(6).Type = 200 'adVarChar
.Parameters(6).Direction = 1 'adParamInput
.Parameters(6).Value = Session("cc_l_name")
'P_SUFFIX
.Parameters(7).Type = 200 'adVarChar
.Parameters(7).Direction = 1 'adParamInput
.Parameters(7).Value = Session("cc_suffix")
'P_ADDRESS
.Parameters(8).Type = 200 'adVarChar
.Parameters(8).Direction = 1 'adParamInput
.Parameters(8).Value = Session("cc_address")
'P_CITY
.Parameters(9).Type = 200 'adVarChar
.Parameters(9).Direction = 1 'adParamInput
.Parameters(9).Value = Session("cc_city")
'P_STATE
.Parameters(10).Type = 200 'adVarChar
.Parameters(10).Direction = 1 'adParamInput
.Parameters(10).Value = Session("cc_state")
'P_ZIP
.Parameters(11).Type = 200 'adVarChar
.Parameters(11).Direction = 1 'adParamInput
.Parameters(11).Value = Session("cc_zip")
'P_AMT
.Parameters(12).Type = 131 'adNumeric
.Parameters(12).Direction = 1 'adParamInput
.Parameters(12).Value = Session("cc_amt")
'P_STATUS
.Parameters(13).Type = 200 'adVarChar
.Parameters(13).Direction = 1 'adParamInput
.Parameters(13).Value = "PENDING"
'P_SOURCE
.Parameters(14).Type = 200 'adVarChar
.Parameters(14).Direction = 1 'adParamInput
.Parameters(14).Value = P_SOURCE
'P_CC_ID
.Parameters(15).Type = 131 'adNumeric
.Parameters(15).Direction = 2 'adParamOutput
'P_ERR_CD
.Parameters(16).Type = 200 'adVarChar
.Parameters(16).Direction = 2 'adParamOutput
'P_ERR_MSG
.Parameters(17).Type = 200 'adVarChar
.Parameters(17).Direction = 2 'adParamOutput
End With
objConnSessionAuth.BeginTrans
cmdCCpayment.Execute
objConnSessionAuth.CommitTrans
</code></pre>
| 3 | 4,041 |
Read text file and name buttons VB.NET
|
<p>What I wan't to do is to read a text file with 1, 2, 3, 4 or 5 lines.
If the text file is completely full (5 lines) then the code works.</p>
<p>But the code needs to work when there are only 3 lines in the text file.
So eventually you get 3 buttons with names and 2 without.</p>
<p>The code:</p>
<pre><code>Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Lines() As String = IO.File.ReadAllLines(file)
Dim Ordernummer1 As String
Dim Ordernummer2 As String
Dim Ordernummer3 As String
Dim Ordernummer4 As String
Dim Ordernummer5 As String
Dim Regels As New List(Of String)
Select Case Lines.Count
Case 1
Lines(1) = ""
Lines(2) = ""
Lines(3) = ""
Lines(4) = ""
Case 2
Lines(2) = ""
Lines(3) = ""
Lines(4) = ""
Case 3
Lines(3) = ""
Lines(4) = ""
Case 4
Lines.add(4) = ""
Case 5
'nothing
End Select
MsgBox(Lines(0))
last = Lines(0).Substring(Lines(0).LastIndexOf("\") + 1)
MsgBox(last)
Ordernummer1 = last.Substring(0, last.IndexOf(" "))
MsgBox(Ordernummer1)
Button12.Text = Ordernummer1
MsgBox(Lines(1))
last = Lines(1).Substring(Lines(1).LastIndexOf("\") + 1)
MsgBox(last)
Ordernummer2 = last.Substring(0, last.IndexOf(" "))
MsgBox(Ordernummer2)
Button13.Text = Ordernummer2
MsgBox(Lines(2))
last = Lines(2).Substring(Lines(2).LastIndexOf("\") + 1)
MsgBox(last)
Ordernummer3 = last.Substring(0, last.IndexOf(" "))
MsgBox(Ordernummer3)
Button14.Text = Ordernummer3
MsgBox(Lines(3))
last = Lines(3).Substring(Lines(3).LastIndexOf("\") + 1)
MsgBox(last)
Ordernummer4 = last.Substring(0, last.IndexOf(" "))
MsgBox(Ordernummer4)
Button15.Text = Ordernummer4
MsgBox(Lines(4))
last = Lines(4).Substring(Lines(4).LastIndexOf("\") + 1)
MsgBox(last)
Ordernummer5 = last.Substring(0, last.IndexOf(" "))
MsgBox(Ordernummer5)
Button16.Text = Ordernummer5
</code></pre>
| 3 | 1,339 |
NullPointerException in spring boot on making request
|
<p>Please help! I use MySQL
<a href="https://i.stack.imgur.com/QOLq7.jpg" rel="nofollow noreferrer">Table structure</a></p>
<p><a href="https://i.stack.imgur.com/7QT8e.jpg" rel="nofollow noreferrer">Table</a></p>
<pre>
java.lang.NullPointerException: null
at com.example.accessingdatamysql.controllers.MainController.RequestAdd(MainController.java:42) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.8.jar:5.3.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.48.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.8.jar:5.3.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.48.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:132) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) ~[spring-security-web-5.4.7.jar:5.4.7]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
</pre>
<p>Models.Users</p>
<pre class="lang-java prettyprint-override"><code>package com.example.accessingdatamysql.models;
import javax.persistence.*;
import java.util.Objects;
@Entity
public class Users {
private int id;
private String username;
private String password;
private int active;
private String role;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "username", nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "active", nullable = false)
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
@Column(name = "role", nullable = false)
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Users users = (Users) o;
return id == users.id && active == users.active && Objects.equals(username, users.username) && Objects.equals(password, users.password) && Objects.equals(role, users.role);
}
@Override
public int hashCode() {
return Objects.hash(id, username, password, active, role);
}
}
</code></pre>
<p>UserRepo</p>
<pre class="lang-java prettyprint-override"><code>package com.example.accessingdatamysql.repo;
import com.example.accessingdatamysql.models.Users;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface UserRepo extends CrudRepository<Users, Integer> {
@Query("select e from Users e where e.username = :username")
Users findUserByUsername(@Param("username") String username);
}
</code></pre>
<p>MainController</p>
<pre class="lang-java prettyprint-override"><code>
package com.example.accessingdatamysql.controllers;
import com.example.accessingdatamysql.models.Request;
import com.example.accessingdatamysql.models.Users;
import com.example.accessingdatamysql.repo.RequestRepo;
import com.example.accessingdatamysql.repo.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.persistence.EntityManager;
import java.security.Principal;
@Controller
public class MainController {
@Autowired
RequestRepo requestRepo;
UserRepo userRepo;
Principal principal;
EntityManager em;
@GetMapping(path = "/")
public String main(Model model, Principal principal) {
Iterable<Request> requests = requestRepo.findAll();
model.addAttribute("user", principal.getName());
model.addAttribute("requests",requests);
return "main";
}
@PostMapping(path = "/request/add")
public String RequestAdd(Principal principal,Model model,@RequestParam long department,long category_id ) {
Users user = userRepo.findUserByUsername(principal.getName());
Request request = new Request(department,category_id, user.getId());
requestRepo.save(request);
return "redirect:/";
}
@GetMapping(path = "/delete/{id}")
public String RequestDetails(Model model, @PathVariable(value = "id") long id) {
requestRepo.deleteById(id);
return "redirect:/";
}
}
</code></pre>
| 3 | 6,656 |
RecyclerView pagination does not load properly?
|
<p>I need to do pagination for recyclerview. That load 20 data firstly. After scroll, it must load 20 data more. But it load this 20 data as a new list and delete old 20 data. How can add them end of first 20? I tried some different ways but I couldn't get JsonArray succesfully.</p>
<pre><code> FirstFragment.java
public class FirstFragment extends Fragment {
RecyclerView recyclerView;
private ArrayList<UserOrder> userOrders;
OrderByPointsAdapter orderByPointsAdapter;
ProgressBar progressBarMain, progressBarRecy;
private NestedScrollView nestedScrollView;
private int xo=0,yo=20;
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.row_first, container, false);
progressBarRecy = view.findViewById(R.id.progressBarFirstRecy);
nestedScrollView = view.findViewById(R.id.nestedRowFirst);
recyclerView = view.findViewById(R.id.recyclerFirstRow);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
loadRecycler(xo,yo);
nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (scrollY == v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight()){
xo = xo+20;
yo = yo +20;
progressBarRecy.setVisibility(View.VISIBLE);
loadRecycler(xo, yo);
}
}
});
return view;
}
private void loadRecycler(int xo, int yo) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.0.35/")
.addConverterFactory(GsonConverterFactory.create())
.build();
//RequestInterface ekliyoruz
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JsonResponse> call = request.getJSON(String.valueOf(xo),String.valueOf(yo));
call.enqueue(new Callback<JsonResponse>() {
@Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
if (response.isSuccessful() && response.body()!= null){
progressBarRecy.setVisibility(View.GONE);
JsonResponse jsonResponse = response.body();
userOrders = new ArrayList<>(Arrays.asList(jsonResponse.getUserOrders()));
orderByPointsAdapter = new OrderByPointsAdapter(userOrders,getActivity().getApplicationContext());
recyclerView.setAdapter(orderByPointsAdapter);
}
}
});
}
</code></pre>
| 3 | 1,369 |
Is it possible to combine mapAreas from ArcGISOnline in one offline map on android?
|
<p>I try to create an offline map using ArcGIS Runtime SDK for Android 100.5.0. I follow preplanned workflow according the guide <a href="https://developers.arcgis.com/android/latest/guide/take-map-offline-preplanned.htm" rel="nofollow noreferrer">https://developers.arcgis.com/android/latest/guide/take-map-offline-preplanned.htm</a>. I create mapAreas in ArcGISOnline and try to download them from device. I want to get an offline map, which contains all mapAreas together like in app maps.me(on a big map you have downloaded regions with deeper detailing), but instead I am getting an offline map made from last downloaded area. So I created mapArea "Europe" with scale world - cities and mapArea "Berlin" with scale cities - buildings (both basemaps - openstreetmaps, no feature layers) and downloaded them successfully, see 2 tpk files in a folder, but mobile_map.mmpk and package.info files only contain data related to last loaded area. Is it possible at all to get what I want, combine tpk files in one map? </p>
<p>My code in Kotlin: </p>
<pre><code> val portal = Portal("https://www.arcgis.com/", false)
val portalItem = PortalItem(portal, itemID)
val offlineMapTask = OfflineMapTask(portalItem)
//get all of the preplanned map areas in the web map
val mapAreasFuture = offlineMapTask.preplannedMapAreasAsync
mapAreasFuture.addDoneListener {
try {
// get the list of areas
val mapAreas = mapAreasFuture.get()
val directory = getDirectory()
prepareDir(directory)
// loop through the map areas
var i = 0
for (mapArea in mapAreas) {
mapArea.loadAsync()
mapArea.addDoneLoadingListener {
val downloadJob = offlineMapTask.downloadPreplannedOfflineMap(mapArea, directory)
downloadJob.start()
downloadJob.addJobDoneListener {
i++
if (i == mapAreas.size) {
val offlineMapPackage = MobileMapPackage(path)
offlineMapPackage.addDoneLoadingListener({
if (offlineMapPackage.getLoadStatus() === LoadStatus.LOADED) {
val mobileMap = offlineMapPackage.getMaps().get(0)
myCompletionFuncToShowMap(mobileMap)
} else {
println("PACKAGING FAILED")
}
})
offlineMapPackage.loadAsync()
}
}
}
}
} catch (e: InterruptedException) {
e.printStackTrace()
} catch (e: Exception) {
e.printStackTrace()
}
</code></pre>
| 3 | 1,448 |
Trying to make a basic parallax website with css
|
<p>So here's my HTML</p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<div class="topbar"></div>
<link rel="stylesheet" href="new.css">
</head>
<body>
<div class="pic1"></div>
<header class="headings">
<h1 align="center">Header</h1>
<h3 align="center">smaller header</h3>
</header>
<form class="form">
<h1>Login</h1>
<input type="text" name="Username" placeholder="Username" autofocus/></br>
<input type="password" name="Password" placeholder="Password"></br>
<input type="submit" name="" value="submit">
</form>
<div class="bottombar">
<h1 align="center"><ins>About Us</ins></h1>
<p>blah blah blah</br>blah blah blah</br>blah blah blah</br></p>
</div>
<div class="pic2"><p>Text 1</p></div>
</body>
</html>
</code></pre>
<p>and here's my CSS for the background images</p>
<pre><code>.pic1{
z-index: 1;
background-image: url("fog.jpg");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0vw, 0vh;
padding-top: 50vh;
padding-bottom: 50vh;
}
.pic2{
z-index: 1;
background-image: url("butterfly.jpg");
background-repeat: no-repeat;
background-attachment: fixed;
top: 115vh;
padding-top: 45vh;
padding-bottom: 35vh;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/Heebn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Heebn.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/a662d.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a662d.jpg" alt="enter image description here" /></a></p>
<p>Hopefully you can see, but thebackground pics dont take up the whole screen, and there's a thin white border around them on the sides. The top bar and About Us bar span the whole page from the left to the right, but not the background pics.</p>
| 3 | 1,069 |
How to make search bar using js
|
<p>WHAT I WANT TO DO : I want to make a search bar for my table using js.</p>
<p>WHAT I HAVE : I have a html table having data from database .</p>
<p>WHAT I TRY : I tried this code to retrieve result but its not working. Here is my full code:</p>
<pre><code><div class="box-tools">
<div class="input-group input-group-sm" style="width: 150px;">
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
</div>
</div>
</div>
<!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="myTable">
<tbody><tr>
<th style="width: 10px">ID</th>
<th>Name</th>
<th>Image</th>
<th style="width: 40px">Action</th>
</tr>
<?php foreach($check as $row)
{?>
<tr>
<td><?php echo $row['cat_id'];?></td>
<td><?php echo $row['category_name'];?></td>
<td><img src="<?php echo $row['category_image'];?>" height="100" width="100"></td>
<td><a href="editcategory.php?id=<?php echo base64_encode($row['cat_id']);?>"><button class=" btn btn-primary btn-warning" >Edit<i class="fa fa-pencil" aria-hidden="true"></i></button></a>
<td><a href="deletecategory.php?id=<?php echo base64_encode($row['cat_id']);?>" class="btn btn-social-icon btn-google"><i class="fa fa fa-trash-o"></i></a>
<?php } ?>
</tr>
</tbody></table>
</div>
<!-- /.box-body -->
</div>
<script>
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
</section>
</div>
</code></pre>
<p>When I try to search it gives me empty results. </p>
| 3 | 1,491 |
ng-repeats mutliple times when i call try call this
|
<p>I am calling ng-repeat on my laravel view ng-repeat call a function from controller that gets the data from database and do some calculations and then reuturing the array but it keeps on returning the data i don't know why can anyone can help me on this why http requests execute multiple times?</p>
<p><strong>Here is the code</strong>
<strong>Laravel View</strong></p>
<pre><code><div ng-controller="HotelsListController as hotelLstCntrl">
<section class="section section-sec top-hotels hotels-sec">
<div class="container">
<div class="section-title">
<h2>Hotels</h2>
</div>
<div class="section-body">
<div class="owl-carousel owl-theme owl-custom-arrow" id="top-hotels">
<div class="item" ng-repeat="hotel_item in hotelLstCntrl.getTopHotels() ">
**This exuecute multiple times**
</div>
</div>
</div>
</div>
</section>
</div>
</code></pre>
<p><strong>angular js controller</strong></p>
<pre><code>(function(){
angular
.module('app')
.controller('HotelsListController',hotelsListController);
hotelsListController.$inject = ['$http','dataService','commonMethods'];
function hotelsListController($http,dataService,commonMethods){
var vm = this;
vm.getHotelsRequests = getHotelData;
vm.getTopHotels = getTopHotels;
function getTopHotels(){
var hotelsLimit = 10;
var top_hotels = [];
//calling the dataService method to get the hotels
dataService.getHotels().then((response)=>{
top_hotels = response.data.data;
});
console.log(top_hotels);
return top_hotels;
}
}
})();
</code></pre>
<p><strong>Data service for getting the requests from api</strong></p>
<pre><code>(function(){
angular
.module('app')
.factory('dataService',DataFactory);
DataFactory.$inject = ['$http']
function DataFactory($http){
var service = {};
service.saveHotels = function(){
return $http.get('/hotels/saveHotelsData');
};
service.getHotels = function(){
return $http.get('/hotels/getHotelsData');
}
return service;
}
})();
</code></pre>
| 3 | 1,180 |
how to run terasort with flink?
|
<p>i just configure my flink cluster (1.0.3 version) and i whanted to run tersort with the flink framework, but its me returned the next erreor, i used this comamnde to run my programm:</p>
<pre><code>/bin/flink run -c --class es.udc.gac.flinkbench.ScalaTeraSort flinkbench-assembly-1.0.jar hdfs://192.168.3.89:8020/teragen/10mo hdfs://192.168.3.89:8020/teragen/rstflink
</code></pre>
<p>and its me return this :</p>
<pre><code>Cluster configuration: Standalone cluster with JobManager at localhost/127.0.0.1:6123
Using address localhost:6123 to connect to JobManager.
JobManager web interface address http://localhost:8081
Starting execution of program
2017-06-23 10:28:43,692 INFO org.apache.hadoop.mapreduce.lib.input.FileInputFormat - Total input paths to process : 2
Spent 2278ms computing base-splits.
Spent 2ms computing TeraScheduler splits.
Computing input splits took 2281ms
Sampling 2 splits of 2
Making -1 from 100000 sampled records
------------------------------------------------------------
The program finished with the following exception:
org.apache.flink.client.program.ProgramInvocationException: The main method caused an error.
at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:545)
at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:419)
at org.apache.flink.client.program.ClusterClient.run(ClusterClient.java:339)
at org.apache.flink.client.CliFrontend.executeProgram(CliFrontend.java:831)
at org.apache.flink.client.CliFrontend.run(CliFrontend.java:256)
at org.apache.flink.client.CliFrontend.parseParameters(CliFrontend.java:1073)
at org.apache.flink.client.CliFrontend$2.call(CliFrontend.java:1120)
at org.apache.flink.client.CliFrontend$2.call(CliFrontend.java:1117)
at org.apache.flink.runtime.security.HadoopSecurityContext$1.run(HadoopSecurityContext.java:43)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1656)
at org.apache.flink.runtime.security.HadoopSecurityContext.runSecured(HadoopSecurityContext.java:40)
at org.apache.flink.client.CliFrontend.main(CliFrontend.java:1116)
Caused by: java.lang.NegativeArraySizeException
at es.udc.gac.flinkbench.terasort.TeraInputFormat$TextSampler.createPartitions(TeraInputFormat.java:103)
at es.udc.gac.flinkbench.terasort.TeraInputFormat.writePartitionFile(TeraInputFormat.java:183)
at es.udc.gac.flinkbench.ScalaTeraSort$.main(ScalaTeraSort.scala:49)
at es.udc.gac.flinkbench.ScalaTeraSort.main(ScalaTeraSort.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:528)
... 13 more
</code></pre>
| 3 | 1,123 |
Catch Jquery UI dialog box event
|
<p>I am having an ajax call. In that ajax call I am passing a json to the server. This happens when the person clicks on the delete button. So, before deleting I am creating a Jquery UI dialog box. In that I am asking user whether he is sure to delete. </p>
<p>Now, my problem is when the user clicks I am not able to catch the event. I am assigning a variable ok to have value when yes or no is clicked in jquery dialog box. But the problem is where I am checking if (ok == 1 ) is called first before the user clicks on yes or no. So in any case if user clicks yes or no the ajax call won't happen.</p>
<p>Both the function is in different scripts file.</p>
<p>The function which does the ajax call is -</p>
<pre><code>$("#delete")
.click(
function() {
var sendData = {};
deleteClicked = 1;
var passedJSON = null;
if (null != selectedRowData) { // if the id in table is not null
if (null != selectedRowId) {
console.log("ID exists --> " + newId);
if (rowclickable == 1 ) { //checking whether row should be deleted or not
var testDate = $("#FromDate").val();
sendData["FromDateStr"] = testDate;
console.log(sendData);
passedJSON = JSON.stringify(sendData);
console.log(passedJSON);
ok = showModalBoxForDelete(ok); // calling the modal box and storing the value
console.log(ok);
if (ok == 1) {
$
.ajax({
type: "POST",
cache: false,
url: deleteURL,
data: passedJSON,
dataType: "json",
cache: false,
async: "true",
contentType: "application/json",
success: function(
data) {
if (1 == data.responseCode) {
$(
"#FromDate,delete")
.attr(
"disabled",
"disabled");
$("#FromDate").datepicker("disable");
table.ajax.reload(null, false); // To load the table
showModalBoxForSuccessfulUpdate("The Goal is Deleted");
} else {
alert(data.responseMessage);
}
},
error: function(data) {
console.log("Server Failure");
}
});
}
}
}
}
</code></pre>
<p>The function which calls the modal box is -</p>
<pre><code>function showModalBoxForDelete(ok){
$("#modelView").dialog({
autoOpen : false,
modal : true,
draggable: false,
buttons : [ {
text : "Yes",
icons : {
primary : "ui-icon-heart"
},
click : function() {
var ok = 1;
$(this).dialog("close");
return ok;
}
}, {
text : "No",
icons : {
primary : "ui-icon-heart"
},
click : function() {
$(this).dialog("close");
console.log("Retaining the page...");
}
} ]
});
$("#modelView" ).dialog("open");
$("#modelView").text("This will delete the goal. Do you still want to continue?");
return ok;
}
</code></pre>
<p>Here the line which checks <code>if (ok == 1)</code> is causing a problem as it will get run before user clicks yes or no.</p>
<p>I am not able to understand what to do now. Can anyone please help?</p>
| 3 | 2,669 |
iOS App Crash: Thread 9: Fatal error: UnsafeBufferPointer has a nil start and nonzero count
|
<p>App is crashing at following line</p>
<p><code>cid = "CID: \(String(describing: Singleton.shared.settings.userName ?? "NA"))"</code></p>
<p>Crashing Code:</p>
<pre><code>static func clientIdFor(basicToken: String) -> String {
var cid: String = ""
if let encodedData = Data(base64Encoded: basicToken, options: .ignoreUnknownCharacters) {
let encodedString = String(data: encodedData, encoding: .utf8) ?? ""
if encodedString.contains(":") {
cid = encodedString.components(separatedBy: ":").first ?? "NA"
} else {
cid = "CID: \(String(describing: Singleton.shared.settings.userName ?? "NA"))" /// <- CRASH
}
}
return cid
}
</code></pre>
<p>Here is backtrace</p>
<pre><code> bt
* thread #9, queue = 'com.apple.root.background-qos', stop reason = Fatal error: UnsafeBufferPointer has a nil start and nonzero count
frame #0: 0x00007fff30a08770 libswiftCore.dylib`_swift_runtime_on_report
frame #1: 0x00007fff30a87579 libswiftCore.dylib`_swift_stdlib_reportFatalErrorInFile + 201
frame #2: 0x00007fff30740c13 libswiftCore.dylib`closure #1 (Swift.UnsafeBufferPointer<Swift.UInt8>) -> () in closure #1 (Swift.UnsafeBufferPointer<Swift.UInt8>) -> () in closure #1 (Swift.UnsafeBufferPointer<Swift.UInt8>) -> () in Swift._assertionFailure(_: Swift.StaticString, _: Swift.StaticString, file: Swift.StaticString, line: Swift.UInt, flags: Swift.UInt32) -> Swift.Never + 387
frame #3: 0x00007fff3074097c libswiftCore.dylib`closure #1 (Swift.UnsafeBufferPointer<Swift.UInt8>) -> () in closure #1 (Swift.UnsafeBufferPointer<Swift.UInt8>) -> () in Swift._assertionFailure(_: Swift.StaticString, _: Swift.StaticString, file: Swift.StaticString, line: Swift.UInt, flags: Swift.UInt32) -> Swift.Never + 300
frame #4: 0x00007fff30740655 libswiftCore.dylib`closure #1 (Swift.UnsafeBufferPointer<Swift.UInt8>) -> () in Swift._assertionFailure(_: Swift.StaticString, _: Swift.StaticString, file: Swift.StaticString, line: Swift.UInt, flags: Swift.UInt32) -> Swift.Never + 117
frame #5: 0x00007fff307402aa libswiftCore.dylib`Swift._assertionFailure(_: Swift.StaticString, _: Swift.StaticString, file: Swift.StaticString, line: Swift.UInt, flags: Swift.UInt32) -> Swift.Never + 314
frame #6: 0x00007fff3074053c libswiftCore.dylib`Swift._fatalErrorMessage(_: Swift.StaticString, _: Swift.StaticString, file: Swift.StaticString, line: Swift.UInt, flags: Swift.UInt32) -> Swift.Never + 44
frame #7: 0x00007fff309a431d libswiftCore.dylib`function signature specialization <Arg[1] = Dead> of generic specialization <Swift.UInt8> of Swift.UnsafeBufferPointer.init(rebasing: Swift.Slice<Swift.UnsafeBufferPointer<τ_0_0>>) -> Swift.UnsafeBufferPointer<τ_0_0> + 109
frame #8: 0x00007fff308ad674 libswiftCore.dylib`Swift._StringGuts.append(Swift._StringGutsSlice) -> () + 500
frame #9: 0x00007fff3084fc0a libswiftCore.dylib`Swift.Character.write<τ_0_0 where τ_0_0: Swift.TextOutputStream>(to: inout τ_0_0) -> () + 26
frame #10: 0x00007fff30735d28 libswiftCore.dylib`Swift.DefaultStringInterpolation.appendInterpolation<τ_0_0 where τ_0_0: Swift.CustomStringConvertible, τ_0_0: Swift.TextOutputStreamable>(τ_0_0) -> () + 40
* frame #11: 0x00000001051e9e45 MY_APP`static UtilityManager.clientIdFor(basicToken="MY_BASIC_TOKEN==", self=MY_APP.UtilityManager) at UtilityManager.swift:213:36
</code></pre>
<p>If I do a <code>po</code> in console, the same line of code works!</p>
<pre><code>po "CID: \(String(describing: Singleton.shared.settings.userName ?? "NA"))"
"CID: NA" /// <- Here it works and prints NA in console.
</code></pre>
<p>I guess by this point in time singleton is not initialized which is why the userName is <code>nil</code></p>
<p>Any idea on why the app is crashing?</p>
| 3 | 1,649 |
How to enlarge tableView on scroll?
|
<p>I'm sorry if this is a duplicate. I tried to review similar questions in SO - still doesn't quite make me understand how to deal with this.</p>
<p>I have a tableView, three textViews and a UIButton. When the user scrolls the tableView, the tableView should pushes the textFields and the button out the image and take up more space. When that is done I want to continue scrolling through the cells.</p>
<p>(I want one of the textFields to always remain and still show the title.) </p>
<p>I think I need to put the textViews and button above the tableView inside a tableView header after which I need to set certain constraints between the UIView above the tableView and tableView itself. Then I need to play around with the UIScrollViewDelegate and calculate something.</p>
<p>As you guys can probably tell, I'm relatively new in programming and I believe this i why I don't quite understand the related questions. And as you can probably tell too, why I am pretty damn confused about how to solve my problem! </p>
<p>Here's a photo of the VC:
<a href="https://i.stack.imgur.com/FxIlj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FxIlj.png" alt="My-VC"></a></p>
<p>I wan't the tableView to go and cover the 'AddNewPersonBtn' and the two bottom textView - leaving only the top textView, the navigationBar and the tableView on the screen. --> Until you then scroll down again and the rest will be visible again. </p>
<p>And here goes the code for the VC:</p>
<pre><code>import UIKit
import RealmSwift
class AllPersonsInYourDiary: UIViewController, UITableViewDelegate, UITableViewDataSource {
var diary: Diaries?
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var showingDiaryName: UILabel!
@IBOutlet weak var showingDiaryQuestion: UILabel!
@IBOutlet weak var showingExtraIdentifer: UILabel!
@IBOutlet weak var diaryTheme: UIImageView!
@IBOutlet weak var diaryPhoto: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView()
self.tableView.tableHeaderView = UIView()
}
override func viewWillAppear(_ animated: Bool) {
tableView.reloadData()
showDiaryIdentifiers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func createNewPersonButton () {
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:
"PersonViewController") as! PersonViewController
controller.mode = .create
controller.diary = diary
self.navigationController?.pushViewController(controller, animated: true)
}
@IBAction func showEditFunc () {
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SettingsVC") as! SettingsVC
controller.diary = diary
self.navigationController?.pushViewController(controller, animated: true)
}
func showDiaryIdentifiers () {
self.showingDiaryName.text = diary?.diaryName
self.showingDiaryQuestion.text = diary?.diaryQuestion
self.showingExtraIdentifer.text = diary?.diaryExtraIdentifier
self.diaryTheme.image = UIImage(data: diary?.diaryTheme ?? Data()) ?? UIImage(named: "Blank")
// self.diaryPhoto.image = UIImage(data: diary?.diaryPhoto ?? Data ()) ?? UIImage(named: "Blank")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return diary!.people.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Person1", for: indexPath) as! PersonCell
let date = DateFormatter.localizedString(from: (diary?.people[indexPath.row].dateCreated)!, dateStyle: .short, timeStyle: .none)
cell.personName.text = diary?.people[indexPath.row].name
cell.personAnswer.text = date
cell.personPhoto.image = UIImage(data: diary?.people[indexPath.row].photo ?? Data()) ?? UIImage(named: "PortaitPhoto")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:
"PersonViewController") as! PersonViewController
controller.person = diary?.people[indexPath.row]
controller.diary = diary
controller.mode = .show
self.navigationController?.pushViewController(controller, animated: true)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let alert = UIAlertController(title: "Are you sure you wish to delete person?", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "No thanks!", style: .cancel)
let action1 = UIAlertAction(title: "Delete!", style: .destructive, handler: { _ in
let realm = try! Realm()
try! realm.write {
guard let person = self.diary?.people[indexPath.row] else {
return
}
self.diary!.people.remove(at: indexPath.row)
realm.delete(person)
}
tableView.deleteRows(at: [indexPath], with: .fade)
})
alert.addAction(action)
alert.addAction(action1)
present(alert, animated: true)
} }
}
</code></pre>
| 3 | 1,816 |
Swift URLSession.shared.dataTask GET Request -1001 returns timeout
|
<p>Sending a POST request to our NGINX Server works good with <code>URLRequest</code> and <code>URLSession.shared.dataTask</code>.
I can login to my app but when I try a GET request my server has no log that the request reached him. Finally I get the timeout error. Important, I am using https. I also tried to use http for GET Requests. on my NGINX Server I set TLS to 1.2 only (I am not a system specialist, I did that in the nginx cfg file. </p>
<blockquote>
<p>Error Domain=NSURLErrorDomain Code=-1001 "Zeitüberschreitung bei der Anforderung." UserInfo={NSUnderlyingError=0x60400005abe0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=<a href="https://myurl" rel="nofollow noreferrer">https://myurl</a>, NSErrorFailingURLKey=<a href="https://myurl" rel="nofollow noreferrer">https://myurl</a>, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=Zeitüberschreitung bei der Anforderung.}</p>
</blockquote>
<p>I am sure that my code for the <code>URLRequest</code> and <code>URLSession</code> is correct because against localhost and our development environment I do not have any of those problems.</p>
<p>Thats my code to create my <code>URLRequest</code></p>
<pre><code>private func buildUrlRequest(jsonObject:[String: Any], connectionType:ConnectionTypes, url:String) -> NSMutableURLRequest? {
let jsonDataSerialized:Data
do {
jsonDataSerialized = try JSONSerialization.data(withJSONObject: jsonObject)
} catch {
return nil
}
var request:NSMutableURLRequest
if nextData {
request = URLRequest(url: URL(string: self.nextRequestPage)!) as! NSMutableURLRequest
} else {
let tString = self.mBaseUrl + url
if let encoded = tString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
var finalurl = URL(string: encoded)
{
if connectionType == .GET {
var tString:String
tString=finalurl.absoluteString
tString = tString.replacingOccurrences(of: "https", with: "http")
finalurl = URL(string:tString)!
}
request = URLRequest(url: finalurl) as! NSMutableURLRequest
} else {
return nil
}
}
request.httpMethod = connectionType.rawValue // i am using enum here
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("no-cache)", forHTTPHeaderField: "Cache-Control")
request.httpBody = jsonDataSerialized
if mUser != nil && mUser.getSessionId() != nil {
request.addValue("Token " + mUser.getSessionId()!, forHTTPHeaderField: "Authorization")
}
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 30.0
return request
}
</code></pre>
<p>This is how I create the task... after the method body I am using <code>task.resume()</code></p>
<pre><code>let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in .... (and so on)
</code></pre>
<p>I spend more than hours to solve this problem... But I have no idea.
I am not sure if the Problem is the Server Config or the Swift code...</p>
| 3 | 1,199 |
Declaring integers in actionPerformed java
|
<p>So I'm trying to create this program in Java that's supposed to keep track of how much stock there is. Like if you wanted to cook pancakes, you would click a button that said "pancakes" and 1xmilk, 2xtimes egg would be removed from the stock every time you click the button, the problem is that I have to declare the integers inside the <code>actionPerformed()</code>, so every time I click the button the original values reset, does any kind soul have the answer? </p>
<pre><code>//1100 Button
JButton bj1100 = new JButton("1100");
f.add(bj1100);
bj1100.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("1100");
//1100 head menu
MAIN f = new MAIN();
f.setLayout(new FlowLayout());
//250/1100 HYDR
JButton bj250HYDR = new JButton("250/1100 HYDR");
f.add(bj250HYDR);
bj250HYDR.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("Building a250/110 HYDR");
//Stock
int lOmaxel =10;
int lVals = 10;
//Orderpoint
int bOmaxel =5;
int bVals = 5;
//Amount to make
int tOmaxel =10;
int tVals =10;
lOmaxel--;
lVals--;
}
});
</code></pre>
| 3 | 1,074 |
Import doesn't work
|
<p>I have a wierd problem. There are two apps in my django project . In one app one of the imports made in views.py is fine but in the other one the same import shows me an error. </p>
<p>Here is views.py where import is fine: </p>
<pre><code>from django.shortcuts import get_object_or_404, render_to_response
from models import Category,Product
from django.template.context import RequestContext
from django.core import urlresolvers
from cart import cart
from catalog.forms import ProductAddToCartForm
from django.http.response import HttpResponseRedirect
# Create your views here.
def index(request, template_name="catalog/index.html"):
page_title = 'Extremely interesting and cheap goods'
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))
def show_category(request,category_slug,template_name='catalog/category.html'):
c = get_object_or_404(Category, slug = category_slug)
products = c.product_set.all()
page_title = c.name
meta_keywords = c.meta_keywords
meta_description = c.meta_description
return render_to_response(template_name,locals(),
context_instance=RequestContext(request))
def show_product(request, product_slug,template_name="catalog/product.html"):
p = get_object_or_404(Product,slug=product_slug)
categories = p.categories.all()
page_title = p.name
meta_keywords = p.meta_keywords
meta_description = p.meta_description
if request.method =='POST':
postdata=request.POST.copy()
form = ProductAddToCartForm(request,postdata)
if form.is_valid():
cart.add_to_cart(request)
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
url = urlresolvers.reverse('show_cart')
return HttpResponseRedirect(url)
else:
form = ProductAddToCartForm(request = request,label_suffix=':')
form.fields['product_slug'].widget.attrs['value'] = product_slug
request.session.set_test_cookie()
return render_to_response("catalog/product.html",locals(),
context_instance=RequestContext(request))
</code></pre>
<p>And here is views.py where import doesn't work:</p>
<pre><code>from django.template.context import RequestContext
from django.shortcuts import render_to_response
from cart import cart
def show_cart(request,template_name="cart/cart.html"):
if request.method == 'POST':
postdata = request.POST.copy()
if postdata['submit'] == 'Remove':
cart.remove_from_cart(request)
if postdata['submit'] == 'Update':
cart.update_cart(request)
cart_items = cart.get_cart_items(request)
page_title = 'Shopping Cart'
cart_subtotal = cart.cart_subtotal(request)
return render_to_response(template_name,locals(),
context_instance=RequestContext(request))
</code></pre>
<p>The import I am speaking about is : from cart import cart. The second views.py is in the same django app where cart.py I am trying to import </p>
| 3 | 1,193 |
yarn run error : Command failed with exit code 1
|
<p>I was trying to follow this <a href="https://lorisleiva.com/create-a-solana-dapp-from-scratch/getting-started-with-solana-and-anchor#:%7E:text=build%0Aanchor%20deploy-,anchor%20run%20test,-Well%2C%20it%20turns" rel="nofollow noreferrer">tutorial</a><br />
This is a tutorial on Solana program dev using anchor and the error rises from using yarn on ubuntu 20.0 i guess
and I got this long error I can't understand
All the help is appreciated</p>
<pre><code>yarn run v1.22.17
warning package.json: No license field
$ /home/sadaf/code/solana-twitter/node_modules/.bin/ts-mocha -p ./tsconfig.json -t 1000000 'tests/**/*.ts'
ReferenceError: TextEncoder is not defined
at Function.fromSecretKey (/home/sadaf/code/solana-twitter/node_modules/@solana/web3.js/src/keypair.ts:66:23)
at Function.local (/home/sadaf/code/solana-twitter/node_modules/@project-serum/anchor/src/nodewallet.ts:13:27)
at Function.env (/home/sadaf/code/solana-twitter/node_modules/@project-serum/anchor/src/provider.ts:79:31)
at Suite.describe (/home/sadaf/code/solana-twitter/tests/solana-twitter.ts:7:38)
at Object.create (/home/sadaf/code/solana-twitter/node_modules/mocha/lib/interfaces/common.js:148:19)
at context.describe.context.context (/home/sadaf/code/solana-twitter/node_modules/mocha/lib/interfaces/bdd.js:42:27)
at Object.<anonymous> (/home/sadaf/code/solana-twitter/tests/solana-twitter.ts:5:1)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Module.m._compile (/home/sadaf/code/solana-twitter/node_modules/ts-node/src/index.ts:439:23)
at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Object.require.extensions.(anonymous function) [as .ts] (/home/sadaf/code/solana-twitter/node_modules/ts-node/src/index.ts:442:12)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.implementationOfRequireOrImportForUnstableEsm [as requireOrImport] (/home/sadaf/code/solana-twitter/node_modules/mocha/lib/nodejs/esm-utils.js:116:12)
at Object.exports.loadFilesAsync (/home/sadaf/code/solana-twitter/node_modules/mocha/lib/nodejs/esm-utils.js:103:34)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code></pre>
| 3 | 1,074 |
Having difficulty with my Monty Hall stimulator code (python)
|
<p><strong>What the Monty Hall game is:</strong></p>
<p>The stage is set up with three large doors labeled #1, #2, and #3. Behind two of the doors is a goat. Behind the other door is a new car. You don’t know which door has the car, but Monty Hall wants you to pick a door. Suppose you pick door #1. Monty Hall then opens one of the other doors (say, door #3) and shows you that there’s a goat behind it. He then says: "I’ll give you a chance to change your mind. Do you want to change your mind and pick door number 2?" After you make a decision, they open the door you finally picked and you find out whether you’ve won a new car or a new goat. To clarify: the locations of the car and the goats are fixed before your game starts. Monty does not get a chance to switch things around in the middle of the game.</p>
<p><strong>What I have to do:</strong> </p>
<p>I need to create a stimulator of the game using Python <strong><em>3</em></strong>. I have to incorporate a random number generator. The program will ask the user for the Random Number generator seed. The goal of a random number generator is to be random. Before my program begins simulating “Let’s Make a Deal,” it's supposed to ask the user for an integer and set it as the seed. If the user gives an input that is not a number, the program should exit immediately by displaying "Seed is not a number!" IF the user gives a number for the input, the game will begin. The game will then ask the user how many games the user wants to run. If the user says 5, the game will repeat five times. Once the game runs the amount of times the user says (like 5), then the game will ask the user AGAIN how many times the user wants to play again.(I'm having difficulty with this looping the game to the number of times the user says and then asking the question once it's done). If the user says 'exit' anytime, the game immediately ends. When asked how many games the user wants to run, if the user does not input a number, the program will just say "Please enter a number" until the user finally enters a number. </p>
<p><strong>What the program has to do:</strong></p>
<p>The program will be easier because it will print the doors AND label which door has a goat or car. So it will display "G" "C" "G" where they will be shuffled for each game so if the program outputted: [C G G] the car would be in door one. Monty (in this case, Monty is just a variable) would "pick" a door where the program randomly generates a number that is either 1, 2, or 3. IF the user picks a door that has the car in it, the program will say the user should stick with the door they picked in order to win. If the user picks a door that has a goat, the program will say that the user should change the door they picked in order to pick the door with the car (I'm stuck at this part). After each set of games, the program gives a summary of how many times the player should have switched and how many times they should have stayed. If the number of games is less than or equal to 10, the program will print out the results of each game. If the result is greater than 10, it will just print the summary.</p>
<p><strong>Example</strong></p>
<p><em>If the input is:</em></p>
<p>25</p>
<p>5</p>
<p>exit</p>
<p><em>Output should be:</em></p>
<p>Enter Random Seed:</p>
<p>Welcome to Monty Hall Analysis</p>
<p>Enter 'exit' to quit.</p>
<p>How many tests should we run?</p>
<p>Game 1</p>
<p>Doors: ['G', 'C', 'G']</p>
<p>Player Selects Door 1</p>
<p>Monty Selects Door 3</p>
<p>Player should switch to win.</p>
<p>Game 2</p>
<p>Doors: ['C', 'G', 'G']</p>
<p>Player Selects Door 1</p>
<p>Monty Selects Door 2</p>
<p>Player should stay to win.</p>
<p>Game 3</p>
<p>Doors: ['G', 'C', 'G']</p>
<p>Player Selects Door 2</p>
<p>Monty Selects Door 1</p>
<p>Player should stay to win.</p>
<p>Game 4</p>
<p>Doors: ['C', 'G', 'G']</p>
<p>Player Selects Door 1</p>
<p>Monty Selects Door 2</p>
<p>Player should stay to win.</p>
<p>Game 5</p>
<p>Doors: ['G', 'C', 'G']</p>
<p>Player Selects Door 3</p>
<p>Monty Selects Door 1</p>
<p>Player should switch to win.</p>
<p>Stay Won 60.0% of the time.</p>
<p>Switch Won 40.0% of the time.</p>
<p>How many tests should we run?</p>
<p>Thank you for using this program.</p>
<p>I am a pretty beginner programmer who's trying to learn so sorry if this is confusing or does not make sense! I have a program so far and I know it's not very good. If someone could help me at all, that would be greatly appreciated. I'm very confused about the randomization aspect of it.</p>
<p><strong>Here is what my program outputs</strong></p>
<p>Enter Random Seed:</p>
<p>Welcome to Monty Hall Analysis</p>
<p>Enter exit to quit.</p>
<p>How many tests should we run?</p>
<p>Seed is not a number!</p>
<p><strong><em>Here is my program:</em></strong></p>
<pre><code>import random
random_seed = input('Enter Random Seed:\n')
try:
random_seed = int(random_seed)
print('Welcome to Monty Hall Analysis')
exit = input('Enter ''exit'' to quit.\n')
tests = int(input('How many tests should we run?\n'))
try:
tests = int(tests)
while True:
select_door = ['G', 'C', 'G']
player_door = input('Doors', random.shuffle(select_door))
doors = [1, 2, 3]
random.choice(doors)
print('Player Selects Door', select_door)
print('Monty Selects Door', random.choice(doors))
if exit == 'exit':
print('Thank you for using this program.')
break
except ValueError:
print('Please enter a number:\n')
except ValueError:
print('Seed is not a number!')
</code></pre>
<p><strong><em>I know the code and my description isn't perfect, but hey I'm trying my best!</em></strong></p>
| 3 | 1,929 |
signing into seedr.cc using requests
|
<p>I am trying to sign into the website seedr.cc, I got names for email and pasword and I don't know the value of submit button, So I gave it <code>Submit</code> as the value and after post() I am checking if it is logged in but it isn't and there happens to be no error so I don't know why it isn't logging in.</p>
<pre><code>import requests
r = requests.session()
res = r.get('http://seedr.cc',headers={'User-Agent':'Chrome/5.0'})
data = {
'username':username,
'password':password,
'sign-in-submit':'Submit',
}
headers = {'User-Agent':'Chrome/5.0',
}
res = r.post('http://seedr.cc',
data=data,
headers=headers,
cookies=r.cookies
)
res=r.get('https://www.seedr.cc/settings',headers=headers,cookies=r.cookies)
</code></pre>
<p>Thanks in Advance</p>
<p>Edit:</p>
<p>This is the form :</p>
<pre><code><form class="sign-in-form" disabled="disabled">
<div class="modal-body">
<div class="row">
<div class="large-12 columns">
<label> <span>Email</span>
<input placeholder="email" name="username" type="text" tabindex="1" required="">
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label> <a id="forgot-password-link">Forgot your password?</a> <span>Password</span>
<input placeholder="password" name="password" pattern=".{6,}" type="password" tabindex="2" title="It must contain the password that you have chosen at registration" required="">
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label style="text-align:center"> <input type="checkbox" name="rememberme" tabindex="3"> <small> Keep me logged in ( <b>this is a private computer</b> )</small> </label>
</div>
</div>
<div class="row">
<!--<div class="large-12 columns" id="login-recaptcha-container" style="text-align:center">
<div id="login-recaptcha" style="max-width: 307px;display: inline-block;"></div><br>
</div>-->
</div>
<div class="large-12 columns" id="premium-bot" style="margin-bottom: 10px;">
<small>* Premium users may skip verification -- <span data-tooltip="" aria-haspopup="true" class="has-tip" data-disable-hover="false" data-selector="tooltip-jt6znnt77" aria-describedby="tooltip-jt6znnt77" title="">why?</span></small>
</div>
</div>
<a class="close-reveal-modal">×</a>
<div class="modal-footer" style="margin: 0 13px 0 13px;border-top: none;">
<button style="margin-bottom:0;background: rgb(80, 139, 208);WIDTH: 100%;border-radius: 5px;" name="sign-in-submit" type="submit" class="button radius" tabindex="5"><i class="fa fa-check"></i> Login</button>
<div id="login-separator">
- OR - </div>
<button type="button" onclick="javascript:FBlogin(false,$(this).closest('form').find('input[name=rememberme]').prop('checked'));return false;" style="margin-bottom:0;background: #354E84;WIDTH: 100%;border-radius: 5px;line-height: 100%;" name="sign-in-submit" class="button radius"><img src="https://static.seedr.cc/images/facebook_icon.png" style="
line-height: 35px;
margin-right: 8px;
vertical-align: -5px;
"> Login with Facebook </button>
<small class="facebook-email-required" style="
text-align: left;
width: 100%;
color: red;
padding: 10px;
display:none;
">Email access is required for login , please try again</small>
</div>
</form>
</code></pre>
| 3 | 2,077 |
Create and fill database from java
|
<p><strong>EDIT: I am using now preparedStatement with the following code:</strong></p>
<pre><code>Statement st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS Xbox_One (id INT AUTO_INCREMENT, "
+ "PRIMARY KEY(id), Thumb VARCHAR (500), Juego VARCHAR(500), URL VARCHAR (200), Lanzamiento VARCHAR (50),Publicado VARCHAR (200), Descripcion TEXT(5000),"
+ "Pegi VARCHAR(10), Descripcion_Pegi VARCHAR (200), nota FLOAT(10,1),"
+ "USA VARCHAR (100), USA_Gold VARCHAR (100), USA_sin_Gold VARCHAR (100), USA_EA VARCHAR (100),"
+ "ARG VARCHAR (100), ARG_Gold VARCHAR (100), ARG_sin_Gold VARCHAR (100), ARG_EA VARCHAR (100),"
+ "AUS VARCHAR (100), AUS_Gold VARCHAR (100), AUS_sin_Gold VARCHAR (100), AUS_EA VARCHAR (100),"
+ "BRA VARCHAR (100), BRA_Gold VARCHAR (100), BRA_sin_Gold VARCHAR (100), BRA_EA VARCHAR (100),"
+ "CAN VARCHAR (100), CAN_Gold VARCHAR (100), CAN_sin_Gold VARCHAR (100), CAN_EA VARCHAR (100),"
+ "SIN VARCHAR (100), SIN_Gold VARCHAR (100), SIN_sin_Gold VARCHAR (100), SIN_EA VARCHAR (100),"
+ "ESP VARCHAR (100), ESP_Gold VARCHAR (100), ESP_sin_Gold VARCHAR (100), ESP_EA VARCHAR (100),"
+ "HK VARCHAR (100), HK_Gold VARCHAR (100), HK_sin_Gold VARCHAR (100), HK_EA VARCHAR (100),"
+ "MEX VARCHAR (100), MEX_Gold VARCHAR (100), MEX_sin_Gold VARCHAR (100), MEX_EA VARCHAR (100),"
+ "COL VARCHAR (100), COL_Gold VARCHAR (100), COL_sin_Gold VARCHAR (100), COL_EA VARCHAR (100),"
+ "HUN VARCHAR (100), HUN_Gold VARCHAR (100), HUN_sin_Gold VARCHAR (100), HUN_EA VARCHAR (100),"
+ "SUD VARCHAR (100), SUD_Gold VARCHAR (100), SUD_sin_Gold VARCHAR (100), SUD_EA VARCHAR (100),"
+ "RUS VARCHAR (100), RUS_Gold VARCHAR (100), RUS_sin_Gold VARCHAR (100), RUS_EA VARCHAR (100),"
+ "CHI VARCHAR (100), CHI_Gold VARCHAR (100), CHI_sin_Gold VARCHAR (100), CHI_EA VARCHAR (100),"
+ "CHINA VARCHAR (100), CHINA_Gold VARCHAR (100), CHINA_sin_Gold VARCHAR (100), CHINA_EA VARCHAR (100),"
+ "IND VARCHAR (100), IND_Gold VARCHAR (100), IND_sin_Gold VARCHAR (100), IND_EA VARCHAR (100),"
+ "JP VARCHAR (100), JP_Gold VARCHAR (100), JP_sin_Gold VARCHAR (100), JP_EA VARCHAR (100),"
+ "KOR VARCHAR (100), KOR_Gold VARCHAR (100), KOR_sin_Gold VARCHAR (100), KOR_EA VARCHAR (100),"
+ "TAI VARCHAR (100), TAI_Gold VARCHAR (100), TAI_sin_Gold VARCHAR (100), TAI_EA VARCHAR (100),"
+ "UK VARCHAR (100), UK_Gold VARCHAR (100), UK_sin_Gold VARCHAR (100), UK_EA VARCHAR (100))"
);
System.out.println( "Tabla creada!");
PreparedStatement ps = con.prepareStatement("INSERT INTO Xbox_One (Juego, URL, Lanzamiento, Publicado, Descripcion, Pegi, Descripcion_Pegi, nota, "
+ "USA, USA_Gold, USA_sin_Gold, USA_EA,"
+ "ARG, ARG_Gold, ARG_sin_Gold, ARG_EA,"
+ "AUS, AUS_Gold, AUS_sin_Gold, AUS_EA,"
+ "BRA, BRA_Gold, BRA_sin_Gold, BRA_EA,"
+ "CAN, CAN_Gold, CAN_sin_Gold, CAN_EA,"
+ "SIN, SIN_Gold, SIN_sin_Gold, SIN_EA,"
+ "ESP, ESP_Gold, ESP_sin_Gold, ESP_EA,"
+ "HK, HK_Gold, HK_sin_Gold, HK_EA,"
+ "MEX, MEX_Gold, MEX_sin_Gold, MEX_EA,"
+ "COL, COL_Gold, COL_sin_Gold, COL_EA,"
+ "HUN, HUN_Gold, HUN_sin_Gold, HUN_EA,"
+ "SUD, SUD_Gold, SUD_sin_Gold, SUD_EA,"
+ "RUS, RUS_Gold, RUS_sin_Gold, RUS_EA,"
+ "CHI, CHI_Gold, CHI_sin_Gold, CHI_EA,"
+ "CHINA, CHINA_Gold, CHINA_sin_Gold, CHINA_EA,"
+ "IND, IND_Gold, IND_sin_Gold, IND_EA,"
+ "JP, JP_Gold, JP_sin_Gold, JP_EA,"
+ "KOR, KOR_Gold, KOR_sin_Gold, KOR_EA,"
+ "TAI, TAI_Gold, TAI_sin_Gold, TAI_EA,"
+ "UK, UK_Gold, UK_sin_Gold, UK_EA)"
+ ") VALUES (?,?,?,?,?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ",?,?,?,?"
+ ")");
</code></pre>
<p><strong>I receive the following error:</strong></p>
<blockquote>
<p>You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')VALUES ('Rocket League','rocket-league/c125w9bg2k0v','2016-02-17','Psyonix, In' at line 1"</p>
</blockquote>
<p><strong>If I try inserting the data manually I have problems too. As you can see the type is VARCHAR.</strong></p>
<p><strong>Edit finished.</strong></p>
<p>I am having problems with the code to introduce data from java to a table in Mysql.</p>
<p>First I create the table if it doesn't exist:</p>
<pre><code> Statement st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS Xbox_One (id INT AUTO_INCREMENT, "
+ "PRIMARY KEY(id), Juego VARCHAR(500), URL VARCHAR (200), Lanzamiento VARCHAR (50), Descripcion TEXT(2000),"
+ "Pegi VARCHAR(10), Descripcion_Pegi VARCHAR (200), nota FLOAT(10,1),"
+ "USA VARCHAR (100), USA_Gold VARCHAR (100), USA_sin_Gold VARCHAR (100), USA_EA VARCHAR (100),"
+ "ARG VARCHAR (100), ARG_Gold VARCHAR (100), ARG_sin_Gold VARCHAR (100), ARG_EA VARCHAR (100),"
+ "AUS VARCHAR (100), AUS_Gold VARCHAR (100), AUS_sin_Gold VARCHAR (100), AUS_EA VARCHAR (100),"
+ "BRA VARCHAR (100), BRA_Gold VARCHAR (100), BRA_sin_Gold VARCHAR (100), BRA_EA VARCHAR (100),"
+ "CAN VARCHAR (100), CAN_Gold VARCHAR (100), CAN_sin_Gold VARCHAR (100), CAN_EA VARCHAR (100),"
+ "SIN VARCHAR (100), SIN_Gold VARCHAR (100), SIN_sin_Gold VARCHAR (100), SIN_EA VARCHAR (100),"
+ "ESP VARCHAR (100), ESP_Gold VARCHAR (100), ESP_sin_Gold VARCHAR (100), ESP_EA VARCHAR (100),"
+ "HK VARCHAR (100), HK_Gold VARCHAR (100), HK_sin_Gold VARCHAR (100), HK_EA VARCHAR (100),"
+ "MEX VARCHAR (100), MEX_Gold VARCHAR (100), MEX_sin_Gold VARCHAR (100), MEX_EA VARCHAR (100),"
+ "COL VARCHAR (100), COL_Gold VARCHAR (100), COL_sin_Gold VARCHAR (100), COL_EA VARCHAR (100),"
+ "HUN VARCHAR (100), HUN_Gold VARCHAR (100), HUN_sin_Gold VARCHAR (100), HUN_EA VARCHAR (100),"
+ "SUD VARCHAR (100), SUD_Gold VARCHAR (100), SUD_sin_Gold VARCHAR (100), SUD_EA VARCHAR (100),"
+ "RUS VARCHAR (100), RUS_Gold VARCHAR (100), RUS_sin_Gold VARCHAR (100), RUS_EA VARCHAR (100),"
+ "CHI VARCHAR (100), CHI_Gold VARCHAR (100), CHI_sin_Gold VARCHAR (100), CHI_EA VARCHAR (100),"
+ "IND VARCHAR (100), IND_Gold VARCHAR (100), IND_sin_Gold VARCHAR (100), IND_EA VARCHAR (100),"
+ "JP VARCHAR (100), JP_Gold VARCHAR (100), JP_sin_Gold VARCHAR (100), JP_EA VARCHAR (100),"
+ "KOR VARCHAR (100), KOR_Gold VARCHAR (100), KOR_sin_Gold VARCHAR (100), KOR_EA VARCHAR (100),"
+ "TAI VARCHAR (100), TAI_Gold VARCHAR (100), TAI_sin_Gold VARCHAR (100), TAI_EA VARCHAR (100),"
+ "UK VARCHAR (100), UK_Gold VARCHAR (100), UK_sin_Gold VARCHAR (100), UK_EA VARCHAR (100))"
);
</code></pre>
<p>This step is correct, the table is created. The problem is that I don't find the way to introduce the data, which is stored in a bidimensional array called listaEmpresaA. </p>
<p>Here is the code I am using:</p>
<pre><code>for (int i = 1; i<listaEmpresaA.length; i++) { //la fila 1 es la del header que no nos interesa
for (int j=0; j<1; j++) {
st.executeUpdate("INSERT INTO Xbox_One (Juego, URL, Publicado, Lanzamiento, Descripcion, Pegi, Descripcion_Pegi, nota, "
+ "USA, USA_Gold, USA_sin_Gold, USA_EA,"
+ "ARG, ARG_Gold, ARG_sin_Gold, ARG_EA,"
+ "AUS, AUS_Gold, AUS_sin_Gold, AUS_EA,"
+ "BRA, BRA_Gold, BRA_sin_Gold, BRA_EA,"
+ "CAN, CAN_Gold, CAN_sin_Gold, CAN_EA,"
+ "SIN, SIN_Gold, SIN_sin_Gold, SIN_EA,"
+ "ESP, ESP_Gold, ESP_sin_Gold, ESP_EA,"
+ "HK, HK_Gold, HK_sin_Gold, HK_EA,"
+ "MEX, MEX_Gold, MEX_sin_Gold, MEX_EA,"
+ "COL, COL_Gold, COL_sin_Gold, COL_EA,"
+ "HUN, HUN_Gold, HUN_sin_Gold, HUN_EA,"
+ "SUD, SUD_Gold, SUD_sin_Gold, SUD_EA,"
+ "RUS, RUS_Gold, RUS_sin_Gold, RUS_EA,"
+ "CHI, CHI_Gold, CHI_sin_Gold, CHI_EA,"
+ "CHINA, CHINA_Gold, CHINA_sin_Gold, CHINA_EA,"
+ "IND, IND_Gold, IND_sin_Gold, IND_EA,"
+ "JP, JP_Gold, JP_sin_Gold, JP_EA,"
+ "KOR, KOR_Gold, KOR_sin_Gold, KOR_EA,"
+ "TAI, TAI_Gold, TAI_sin_Gold, TAI_EA,"
+ "UK, UK_Gold, UK_sin_Gold, UK_EA)"
+ ") VALUES ('"
+listaEmpresaA[i][j]+"','"+listaEmpresaA[i][j+1]+"','"+listaEmpresaA[i][j+2]+"', '"+listaEmpresaA[i][j+3]+"', '"+listaEmpresaA[i][j+4]+"', '"+listaEmpresaA[i][j+5]+"'"
+listaEmpresaA[i][j+6]+"','"+listaEmpresaA[i][j+7]+"',"
+ "'"+listaEmpresaA[i][j+8]+"', '"+listaEmpresaA[i][j+9]+"'"
+listaEmpresaA[i][j+10]+"','"+listaEmpresaA[i][j+11]+"','"+listaEmpresaA[i][j+12]+"', '"+listaEmpresaA[i][j+13]+"'"
+listaEmpresaA[i][j+14]+"','"+listaEmpresaA[i][j+15]+"','"+listaEmpresaA[i][j+16]+"', '"+listaEmpresaA[i][j+17]+"'"
+listaEmpresaA[i][j+18]+"','"+listaEmpresaA[i][j+19]+"','"+listaEmpresaA[i][j+20]+"', '"+listaEmpresaA[i][j+21]+"'"
+listaEmpresaA[i][j+22]+"','"+listaEmpresaA[i][j+23]+"','"+listaEmpresaA[i][j+24]+"', '"+listaEmpresaA[i][j+25]+"'"
+listaEmpresaA[i][j+26]+"','"+listaEmpresaA[i][j+27]+"','"+listaEmpresaA[i][j+28]+"', '"+listaEmpresaA[i][j+29]+"'"
+listaEmpresaA[i][j+30]+"','"+listaEmpresaA[i][j+31]+"','"+listaEmpresaA[i][j+32]+"', '"+listaEmpresaA[i][j+33]+"'"
+listaEmpresaA[i][j+34]+"','"+listaEmpresaA[i][j+35]+"','"+listaEmpresaA[i][j+36]+"', '"+listaEmpresaA[i][j+37]+"'"
+listaEmpresaA[i][j+38]+"','"+listaEmpresaA[i][j+39]+"','"+listaEmpresaA[i][j+40]+"', '"+listaEmpresaA[i][j+41]+"'"
+listaEmpresaA[i][j+42]+"','"+listaEmpresaA[i][j+43]+"','"+listaEmpresaA[i][j+44]+"', '"+listaEmpresaA[i][j+45]+"'"
+listaEmpresaA[i][j+46]+"','"+listaEmpresaA[i][j+47]+"','"+listaEmpresaA[i][j+48]+"', '"+listaEmpresaA[i][j+49]+"'"
+listaEmpresaA[i][j+50]+"','"+listaEmpresaA[i][j+51]+"','"+listaEmpresaA[i][j+52]+"', '"+listaEmpresaA[i][j+53]+"'"
+listaEmpresaA[i][j+54]+"','"+listaEmpresaA[i][j+55]+"','"+listaEmpresaA[i][j+56]+"', '"+listaEmpresaA[i][j+57]+"'"
+listaEmpresaA[i][j+58]+"','"+listaEmpresaA[i][j+59]+"','"+listaEmpresaA[i][j+60]+"', '"+listaEmpresaA[i][j+61]+"'"
+listaEmpresaA[i][j+62]+"','"+listaEmpresaA[i][j+63]+"','"+listaEmpresaA[i][j+64]+"', '"+listaEmpresaA[i][j+65]+"'"
+listaEmpresaA[i][j+66]+"','"+listaEmpresaA[i][j+67]+"','"+listaEmpresaA[i][j+68]+"', '"+listaEmpresaA[i][j+69]+"'"
+listaEmpresaA[i][j+70]+"','"+listaEmpresaA[i][j+71]+"','"+listaEmpresaA[i][j+72]+"', '"+listaEmpresaA[i][j+73]+"'"
+listaEmpresaA[i][j+74]+"','"+listaEmpresaA[i][j+75]+"','"+listaEmpresaA[i][j+76]+"', '"+listaEmpresaA[i][j+77]+"'"
+listaEmpresaA[i][j+78]+"','"+listaEmpresaA[i][j+79]+"','"+listaEmpresaA[i][j+80]+"', '"+listaEmpresaA[i][j+81]+"'"
+listaEmpresaA[i][j+82]+"','"+listaEmpresaA[i][j+83]+"','"+listaEmpresaA[i][j+84]+"', '"+listaEmpresaA[i][j+85]+"'"
+listaEmpresaA[i][j+86]+"','"+listaEmpresaA[i][j+87]+"','"+listaEmpresaA[i][j+88]+"', '"+listaEmpresaA[i][j+89]+"'"
+listaEmpresaA[i][j+90]+"','"+listaEmpresaA[i][j+91]+"','"+listaEmpresaA[i][j+92]+"', '"+listaEmpresaA[i][j+93]+"'"
+listaEmpresaA[i][j+94]+"','"+listaEmpresaA[i][j+95]+"'"
+ ")");
}
}
</code></pre>
<p>Could be a little bit messy but I haven't found any other way to do it.</p>
<p>I would appreciate if you could give me some tips or point at the error(s). There is no error in the execution. </p>
<p>Thanks in advice.</p>
| 3 | 7,948 |
How to fix value update delay in vuejs after axios request?
|
<p>I am retrieving a list of data from an api and need to fill the specific <code><select></select></code> tags, which is associated to a few radio button, with some of the data as <code><options></options></code>. The radio buttons waiting for an event (<code>@change</code>/<code>@click</code>) and executing and axios get request. Everthing works fine. I click on a radio button and retrieving the data as response (vue tools also showing the right data) but the <code><option></option></code> tags are not updating. Now when I click on another radio button, I am getting again the right data from the api BUT now the <code><option></option></code> tags are refreshing with the data from the previous response.</p>
<p>Template</p>
<pre><code><!-- CREATING 7 RADIO BUTTONS FOR THE CURRENT WEEK FROM MON-SUN -->
<div class="wrapper" v-for="item in inputDetails">
<input :id="'datetime[0]['+item.labelText+']'" type="radio" name="datetime[0][date]" v-model="formData.datetime[0].date" :value="item.inputValue" @change="getTimes" />
</div>
<!-- CREATING THE TIME PICKER -->
<select id="datetime[0][time]" name="datetime[0][time]" v-model="formData.datetime[0].time">
<option selected="selected"></option>
<option v-for="item in selectOptionTimes[0]" :value="item.value">{{ item.label }}</option>
</select>
<!--
2 MORE RADIO BUTTON SECTION AND TIME PICKER SECTIONS WITH DIFFERENT INDEXES
<input id="datetime[1][time]"...
-->
</code></pre>
<p>Script</p>
<pre><code>data() {
return {
formData: {
datetime: [
{date: '', time: ''},
{date: '', time: ''},
{date: '', time: ''},
]
}
selectOptionTimes: [],
}
},
methods: {
getTimes: function (current) {
let instanceIndex = current.currentTarget.id.match(/(?<=\[)([0-9])(?=])/g)[0]; // getting the index of the current datetime section
axios.get('/api-url', {
params: {
location_id: this.formData.location_id,
date: current.currentTarget.value
}
}).then(response => {
this.selectOptionTimes[instanceIndex] = response.data;
});
}
}
</code></pre>
<p>Does someone know what the problem is here?</p>
| 3 | 1,100 |
Count and filter with Group By; and Rows to Columns conversion
|
<p>I have two Tables</p>
<ol>
<li>Task</li>
<li>TaskDetail</li>
</ol>
<p>Task:</p>
<pre><code>| TaskName |Department|TaskStatus|DetailID |
|--------- |--------- |--------- |--------- |
| T1 | D1 | 31 | 1 |
| T1 | D2 | 32 | 2 |
| T1 | D3 | 31 | 3 |
</code></pre>
<ul>
<li><p>Task 【T1】 is assigned to three departments 【D1, D2, D3】</p>
</li>
<li><p>Each department has a different DeatilID for each task.</p>
</li>
<li><p>there can be at most three TaskStatus: 30,31,32</p>
</li>
</ul>
<p>TaskDetail:</p>
<pre><code>|DetailID | AssetCode | CodeStatus |
|------- |------------ |------------ |
| 1 | AC1 | 14 |
| 1 | AC2 | 14 |
| 1 | AC3 | 15 |
| 1 | AC4 | 16 |
| 1 | AC5 | 14 |
| 1 | AC6 | 16 |
| 2 | AC7 | 16 |
| 2 | AC8 | 16 |
| 2 | AC9 | 16 |
| 2 | AC10 | 16 |
| 2 | AC11 | 16 |
| 3 | AC10 | 15 |
| 3 | AC11 | 14 |
</code></pre>
<ul>
<li>TaskDetail has different asset codes for each department</li>
<li>There can be at most three CodeStatus: 14, 15, 16</li>
</ul>
<p>Desired Results:</p>
<pre><code>| Row_ID | TaskName |Department|TaskStatus|DetailID |Count(14) |Count(15) |Count(16) |
|--------- |--------- |--------- |--------- |--------- |--------- |--------- |--------- |
| 1 | T1 | D1 | 31 | 1 | 3 | 1 | 2 |
| 2 | T1 | D2 | 30 | 2 | 0 | 0 | 5 |
| 3 | T1 | D3 | 32 | 3 | 0 | 1 | 1 |
</code></pre>
<ul>
<li><p>TaskStatus is based on the CodeStatuses in TaskDetail Table</p>
<pre><code> if(count(16) = all) then TaskStatus 30; //as in Row_ID 2
if(count(14)>=0 || count(15)>=0) then TaskStatus 31; //as in Row_ID 1
if(count(16)==0) then TaskStatus 32; //as in Row_ID 3
</code></pre>
</li>
<li><p>The same CodeStatus are counted for each department based on the TaskName and placed in the columns Count(14), Count(15), and Count(16). For instance:</p>
<pre><code> Count(14)= Count of all CodeStatus = 14
Count(15)= Count of all CodeStatus = 15
Count(16)= Count of all CodeStatus = 16
</code></pre>
</li>
</ul>
| 3 | 1,413 |
How do I access the $ref in the JSON recursively as to complete the whole JSON?
|
<p>I have this schema, which has <code>$ref</code> in it. I need to recursively (assuming there are no infinite cycles) fill in references. That is, wherever <code>$ref</code> is present, the whole object is replaced with what it points.</p>
<p>Note, I can't use any libraries and need to write the Class/function on my own. I did see <a href="https://github.com/gazpachoking/jsonref/blob/master/jsonref.py" rel="nofollow noreferrer">jsonref</a> but was unable to understand the LazyLoad and the callbacks.</p>
<p>Could it be done in a simpler way? I've been trying to do this for days.</p>
<pre><code>{
"definitions": {
"pet": {
"type": "object",
"properties": {
"name": { "type": "string" },
"breed": { "type": "string" },
"age": { "type": "string" }
},
"required": ["name", "breed", "age"]
}
},
"type": "object",
"properties": {
"cat": { "$ref": "#/definitions/pet" },
"dog": { "$ref": "#/definitions/pet" }
}
}
</code></pre>
<p>becomes, </p>
<pre><code>{
"definitions": {
"pet": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"breed": {
"type": "string"
},
"age": {
"type": "string"
}
},
"required": [
"name",
"breed",
"age"
]
}
},
"type": "object",
"properties": {
"cat": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"breed": {
"type": "string"
},
"age": {
"type": "string"
}
},
"required": [
"name",
"breed",
"age"
]
},
"dog": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"breed": {
"type": "string"
},
"age": {
"type": "string"
}
},
"required": [
"name",
"breed",
"age"
]
}
}
}
</code></pre>
<p>This is the JSON I'm trying to solve, thanks.</p>
<pre><code>{
"$id": "https://example.com/nested-schema.json",
"title": "nested-schema",
"$schema": "http://json-schema.org/draft-07/schema#",
"required": [
"Music",
"MusicID",
"Composer"
],
"properties": {
"MusicID": {
"type": "string",
"minLength": 0,
"maxLength": 0
},
"Music": {
"$ref": "#/definitions/Music"
},
"Composer": {
"type": "integer",
"minimum": 0,
"maximum": 0
}
},
"definitions": {
"Music": {
"type": "object",
"required": [
"Date"
],
"properties": {
"Date": {
"type": "string",
"format": "date"
},
"Artist": {
"$ref": "#/definitions/AlbumInformation"
}
}
},
"AlbumInformation": {
"type": "object",
"required": [
"Name"
],
"properties": {
"Name": {
"type": "string",
"minLength": 5
}
}
}
},
"description": "nested-schema"
}
</code></pre>
<p>Help will be deeply appreciated, thanks.</p>
<p>Some code that I have been trying:</p>
<pre><code>@classmethod
def replace_refs(cls, obj, _recursive=False, **kwargs):
kwargs["_recursive"] = True
path = list(kwargs.pop("_path", ()))
if isinstance(obj, Mapping):
for k, v in obj.items():
if isinstance(v, dict):
if '$ref' in v:
import pdb
print(k, v)
cls.replace_refs(v)
return obj
</code></pre>
| 3 | 1,894 |
How to implement specification pattern?
|
<p>In my project; I have included specific pattern classes that are given below. I dont know how to implement this. These codes are included by previous developers.</p>
<pre><code>public interface ISpecification<T>
{
Expression<Func<T, bool>> SpecExpression { get; }
bool IsSatisfiedBy(T obj);
}
public static class IExtensions
{
public static ISpecification<T> And<T>(
this ISpecification<T> left,
ISpecification<T> right)
{
return new And<T>(left, right);
}
public static ISpecification<T> Or<T>(
this ISpecification<T> left,
ISpecification<T> right)
{
return new Or<T>(left, right);
}
public static ISpecification<T> Negate<T>(this ISpecification<T> inner)
{
return new Negated<T>(inner);
}
}
public abstract class SpecificationBase<T> : ISpecification<T>
{
private Func<T, bool> _compiledExpression;
private Func<T, bool> CompiledExpression
{
get { return _compiledExpression ?? (_compiledExpression = SpecExpression.Compile()); }
}
public abstract Expression<Func<T, bool>> SpecExpression { get; }
public bool IsSatisfiedBy(T obj)
{
return CompiledExpression(obj);
}
}
public class And<T> : SpecificationBase<T>
{
ISpecification<T> left;
ISpecification<T> right;
public And(
ISpecification<T> left,
ISpecification<T> right)
{
this.left = left;
this.right = right;
}
// AndSpecification
public override Expression<Func<T, bool>> SpecExpression
{
get
{
var objParam = Expression.Parameter(typeof(T), "obj");
var newExpr = Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(
Expression.Invoke(left.SpecExpression, objParam),
Expression.Invoke(right.SpecExpression, objParam)
),
objParam
);
return newExpr;
}
}
}
public class Or<T> : SpecificationBase<T>
{
ISpecification<T> left;
ISpecification<T> right;
public Or(
ISpecification<T> left,
ISpecification<T> right)
{
this.left = left;
this.right = right;
}
// OrSpecification
public override Expression<Func<T, bool>> SpecExpression
{
get
{
var objParam = Expression.Parameter(typeof(T), "obj");
var newExpr = Expression.Lambda<Func<T, bool>>(
Expression.OrElse(
Expression.Invoke(left.SpecExpression, objParam),
Expression.Invoke(right.SpecExpression, objParam)
),
objParam
);
return newExpr;
}
}
}
public class Negated<T> : SpecificationBase<T>
{
private readonly ISpecification<T> _inner;
public Negated(ISpecification<T> inner)
{
_inner = inner;
}
// NegatedSpecification
public override Expression<Func<T, bool>> SpecExpression
{
get
{
var objParam = Expression.Parameter(typeof(T), "obj");
var newExpr = Expression.Lambda<Func<T, bool>>(
Expression.Not(
Expression.Invoke(this._inner.SpecExpression, objParam)
),
objParam
);
return newExpr;
}
}
}
</code></pre>
<p>How to implement above specification with a simple example? What is the use of this specification?</p>
| 3 | 1,834 |
AngularJS and WordPress API display data from single post
|
<p>I'm using the WordPress API as a data service to an AngularJS/Ionic app. I have a post type called programmes and have a list of programmes (posts) and the JSON looks like:</p>
<pre><code>var programmes = [
{
id: 6,
title: "A post",
slug: "a-post"
},
{
id: 7,
title: "Another post",
slug: "another-post"
},
{
id: 8,
title: "Post 123",
slug: "post-123"
}
]
</code></pre>
<p>I've got the list of programmes displaying with ngRepeat. However I'm struggling to get the data for an individual post.</p>
<p>I was trying to do it like so to get data for the single programme: <code>var programme = programmes[$stateParams.programmeId];</code> however the issue is, for example, if I click on the first "A post" it returns <code>6</code> from the programme id but this does not match the index of the object which is <code>0</code>.</p>
<p>How can I get data from a single programme when the id and index do not match without having to manually reset the programme id's in the database?</p>
<p>Here are my files so far:</p>
<p><strong>app.js</strong></p>
<pre><code>.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.programmes', {
url: "/programmes",
views: {
'menuContent': {
templateUrl: "templates/programmes.html",
controller: 'ProgrammesCtrl'
}
}
})
.state('app.programme', {
url: "/programmes/:programmeSlug",
views: {
'menuContent': {
templateUrl: "templates/programme.html",
controller: 'ProgrammeCtrl'
}
}
})
$urlRouterProvider.otherwise('/app/programmes');
});
</code></pre>
<p><strong>data.js</strong></p>
<pre><code>.factory('DataFactory', function($http) {
var urlBase = 'http://event-app.dev/wp-json/wp/v2';
var APIdata = {};
var currentProgramme = null;
return {
getProgrammes: function() {
return $http.get(urlBase + '/programmes');
}
}
})
</code></pre>
<p><strong>controllers.js</strong></p>
<pre><code>.controller ('ProgrammesCtrl', function ($scope, DataFactory) {
getProgrammes();
function getProgrammes() {
DataFactory.getProgrammes().then(function(response) {
$scope.programmes = response.data;
},
function(error) {
$scope.status = 'Unable to load data';
});
}
})
.controller ('ProgrammeCtrl', function ($scope, $stateParams, DataFactory) {
getProgrammes();
function getProgrammes() {
DataFactory.getProgrammes().then(function(response, id) {
var programmes = response.data;
$scope.programme = programmes[$stateParams.programmeId];
},
function(error) {
$scope.status = 'Unable to load data';
});
}
})
</code></pre>
<p><strong>programme.html (view to display a single programme)</strong></p>
<pre><code><ion-view view-title="{{programme.title}}">
<ion-content>
<ion-list>
<ion-item>
{{programme.title}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
</code></pre>
| 3 | 1,199 |
*ngFor not showing any data
|
<p>I'm creating a chatting app. I have a slight problem, <code>ngFor</code> doesnt seem to work for me.</p>
<p>I have 2 components, 1 is the feed which holds the other component which is the message. So feed shows a list of message components.</p>
<p>Feed
.ts</p>
<pre><code>import { Component, OnInit, OnChanges } from '@angular/core';
import { Observable } from 'rxjs';
import { Message } from '../models/message';
import { MessageService } from '../core/message.service';
@Component({
selector: 'app-feed',
templateUrl: './feed.component.html',
styleUrls: ['./feed.component.css']
})
export class FeedComponent implements OnInit, OnChanges {
feed: Observable<Message[]>;
constructor(private msgService: MessageService) { }
getMessages(): Observable<Message[]> {
return this.msgService.getAllMessages();
}
ngOnInit() {
this.feed = this.getMessages();
}
ngOnChanges() {
this.feed = this.getMessages();
}
}
</code></pre>
<p>Feed .html</p>
<pre><code><div class="feed">
<div *ngIf="feed | async; then fetched else fetching">
</div>
<ng-template #fetched>
<div *ngFor="let message of feed$ | async" class="message">
<app-message [message]=message></app-message>
</div>
</ng-template>
<ng-template #fetching>
<h3>Loading...</h3>
</ng-template>
</div>
</code></pre>
<p>Message .ts</p>
<pre><code>import { Component, OnInit, Input } from '@angular/core';
import { Message } from '../models/message';
@Component({
selector: 'app-message',
templateUrl: './message.component.html',
styleUrls: ['./message.component.css']
})
export class MessageComponent implements OnInit {
@Input() message: Message;
sender: string;
body: string;
createdAt: string;
constructor() { }
ngOnInit(message = this.message) {
this.sender = message.Sender;
this.body = message.Body;
this.createdAt = message.CreatedAt;
}
}
</code></pre>
<p>Message .html</p>
<pre><code><div class="messageContainer">
<div class="messageData">
<span class="sender">
<p>{{sender}}</p>
</span>
<span class="createdAt">
<p>{{createdAt | date:'medium'}}</p>
</span>
</div>
<div class="messageContent">
{{body}}
</div>
</div>
</code></pre>
<p>Also here is my service which does an API call from my asp.net project.</p>
<p>MessageService .ts</p>
<pre><code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Message } from '../models/message';
@Injectable({
providedIn: 'root'
})
export class MessageService {
private readonly baseUrl = 'http://localhost:50169';
constructor(private http: HttpClient) { }
getAllMessages(): Observable<Message[]> {
return this.http.get<Message[]>(`${this.baseUrl}/api/messages`);
}
}
</code></pre>
<p>I've tried checking the value of the API call and it has value based on the console log.</p>
<p>My problem is it does not show any data on the <code>ngFor</code> of the feed component.</p>
| 3 | 1,223 |
Configuration issue in HermesJMS - java.lang.NoClassDefFoundError for BeanSupport class
|
<p>I am trying to test a message using HermesJMS. I am getting a <code>java.lang.NoClassDefFoundError</code> for the <code>BeanSupport</code> class. What could be the issue?</p>
<p>I have configured the required jars under specific path and configured the same in hermes-config.xml within the tag <code></classpathGroup></code>.
The <code>org.apache.activemq.artemis.utils.uri.BeanSupport</code> is present in <code>artemis-commons-2.0.0.jar</code> which is already included in classpathGroup which I am able to view under Options->Configuration->Providers in HermesJMS.
I have included all the required jars and configured the same.
Few blogs suggested that the version of jar might be the cause of the issue. I tried all versions of artemis-commons jar yet, I am getting the same error.
Kindly suggest your views on the issue. </p>
<p>The complete stack of the error message :</p>
<pre><code>java.lang.NoClassDefFoundError: Could not initialize class org.apache.activemq.artemis.utils.uri.BeanSupport
at org.apache.activemq.artemis.uri.schema.serverLocator.AbstractServerLocatorSchema.newConnectionOptions(AbstractServerLocatorSchema.java:29)
at org.apache.activemq.artemis.uri.schema.serverLocator.TCPServerLocatorSchema.internalNewObject(TCPServerLocatorSchema.java:42)
at org.apache.activemq.artemis.uri.schema.serverLocator.TCPServerLocatorSchema.internalNewObject(TCPServerLocatorSchema.java:33)
at org.apache.activemq.artemis.utils.uri.URISchema.newObject(URISchema.java:86)
at org.apache.activemq.artemis.utils.uri.URISchema.newObject(URISchema.java:30)
at org.apache.activemq.artemis.utils.uri.URIFactory.newObject(URIFactory.java:59)
at org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl.newLocator(ServerLocatorImpl.java:411)
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.<init>(ActiveMQConnectionFactory.java:209)
at org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory.<init>(ActiveMQConnectionFactory.java:202)
at org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory.<init>(ActiveMQJMSConnectionFactory.java:34)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jboss.marshalling.reflect.SerializableClass.invokeConstructor(SerializableClass.java:340)
at org.jboss.marshalling.reflect.SerializableClass.callNoArgConstructor(SerializableClass.java:292)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadNewObject(RiverUnmarshaller.java:1408)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:272)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:205)
at org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:41)
at org.wildfly.naming.client.remote.RemoteClientTransport.lookup(RemoteClientTransport.java:243)
at org.wildfly.naming.client.remote.RemoteContext.lambda$lookupNative$0(RemoteContext.java:190)
at org.wildfly.naming.client.NamingProvider.performExceptionAction(NamingProvider.java:222)
at org.wildfly.naming.client.remote.RemoteContext.performWithRetry(RemoteContext.java:100)
at org.wildfly.naming.client.remote.RemoteContext.lookupNative(RemoteContext.java:188)
at org.wildfly.naming.client.AbstractFederatingContext.lookup(AbstractFederatingContext.java:74)
at org.wildfly.naming.client.store.RelativeFederatingContext.lookupNative(RelativeFederatingContext.java:58)
at org.wildfly.naming.client.AbstractFederatingContext.lookup(AbstractFederatingContext.java:74)
at org.wildfly.naming.client.AbstractFederatingContext.lookup(AbstractFederatingContext.java:60)
at org.wildfly.naming.client.AbstractFederatingContext.lookup(AbstractFederatingContext.java:66)
at org.wildfly.naming.client.WildFlyRootContext.lookup(WildFlyRootContext.java:144)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at hermes.JNDIConnectionFactory.createConnection(JNDIConnectionFactory.java:105)
at hermes.impl.jms.ConnectionManagerSupport.createConnection(ConnectionManagerSupport.java:126)
at hermes.impl.jms.ConnectionManagerSupport.createConnection(ConnectionManagerSupport.java:92)
at hermes.impl.jms.ConnectionSharedManager.reconnect(ConnectionSharedManager.java:81)
at hermes.impl.jms.ConnectionSharedManager.connect(ConnectionSharedManager.java:91)
at hermes.impl.jms.ConnectionSharedManager.getConnection(ConnectionSharedManager.java:104)
at hermes.impl.jms.ConnectionSharedManager.getObject(ConnectionSharedManager.java:142)
at hermes.impl.jms.ThreadLocalSessionManager.connect(ThreadLocalSessionManager.java:190)
at hermes.impl.jms.ThreadLocalSessionManager.getSession(ThreadLocalSessionManager.java:570)
at hermes.impl.jms.AbstractSessionManager.getDestination(AbstractSessionManager.java:460)
at hermes.impl.DefaultHermesImpl.getDestination(DefaultHermesImpl.java:367)
at hermes.browser.tasks.BrowseDestinationTask.invoke(BrowseDestinationTask.java:141)
at hermes.browser.tasks.TaskSupport.run(TaskSupport.java:175)
at hermes.browser.tasks.ThreadPool.run(ThreadPool.java:170)
at java.lang.Thread.run(Thread.java:748)
</code></pre>
| 3 | 1,745 |
Print to the IDLE Shell when a tkinter button is pressed
|
<p>I am trying to create a small window that shows up in the corner of your screen. The window will have a keyboard on it. I want to be able to make the computer think that you pressed a button on your keyboard when a button in the window is pressed. This is the code I have so far:</p>
<pre><code>from tkinter import *
top = Tk()
frame1 = Frame(top)
btn = Button(frame1,text="q",command= 'print("q",end="")')
btn2 = Button(frame1,text="w",command= 'print("w",end="")')
btn3 = Button(frame1,text="e",command= 'print("e",end="")')
btn4 = Button(frame1,text="r",command= 'print("r",end="")')
btn5 = Button(frame1,text="t",command= 'print("t",end="")')
btn6 = Button(frame1,text="y",command= 'print("y",end="")')
btn7 = Button(frame1,text="u",command= 'print("u",end="")')
btn8 = Button(frame1,text="i",command= 'print("i",end="")')
btn9 = Button(frame1,text="o",command= 'print("o",end="")')
btn10 = Button(frame1,text="p",command='print("p",end="")')
frame2 = Frame(top)
btn11 = Button(frame2,text="a",command='print("a",end="")')
btn12 = Button(frame2,text="s",command='print("s",end="")')
btn13 = Button(frame2,text="d",command='print("d",end="")')
btn14 = Button(frame2,text="f",command='print("f",end="")')
btn15 = Button(frame2,text="g",command='print("g",end="")')
btn16 = Button(frame2,text="h",command='print("h",end="")')
btn17 = Button(frame2,text="j",command='print("j",end="")')
btn18 = Button(frame2,text="k",command='print("k",end="")')
btn19 = Button(frame2,text="l",command='print("l",end="")')
frame3 = Frame(top)
btn20 = Button(frame3,text="z",command='print("z",end="")')
btn21 = Button(frame3,text="x",command='print("x",end="")')
btn22 = Button(frame3,text="c",command='print("c",end="")')
btn23 = Button(frame3,text="v",command='print("v",end="")')
btn24 = Button(frame3,text="b",command='print("b",end="")')
btn25 = Button(frame3,text="n",command='print("n",end="")')
btn26 = Button(frame3,text="m",command='print("m",end="")')
btnArr1 = [btn,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btn10]
btnArr2 = [btn11,btn12,btn13,btn14,btn15,btn16,btn17,btn18,btn19]
btnArr3 = [btn20,btn21,btn22,btn23,btn24,btn25,btn26]
for x in range(0,len(btnArr1),1):
btnArr1[x].pack(side=LEFT)
frame1.pack()
for x in range(len(btnArr2)-1,-1,-1):
btnArr2[x].pack(side=RIGHT)
frame2.pack()
for x in range(len(btnArr3)-1,-1,-1):
btnArr3[x].pack(side=RIGHT)
frame3.pack()
top.mainloop()
</code></pre>
<p>When I run it, it does nothing. I tried using the plain code without the single quotes, and I tried using an <code>exec()</code> statement in the command parameter. Both tries failed. </p>
<p>I am using python 3.6.2</p>
<p>If anyone has any idea why this is, I would love to hear what you have to say. Thank you for your time! </p>
| 3 | 1,076 |
No load data anymore except refresh action
|
<p>I couldn't find a solution to my problem on the search engine, So i decided to ask here.</p>
<p>I have navigation tab with 3 fragments <code>fragmentA, fragmentB, fragmentC</code>. Each fragment load data from parsed data. i have opened fragment a and load data on listview, then i want to change to fragment b, and load the data too. but when i want to go back to fragmentA the fragment loads the data again.</p>
<p>I want my fragment are saving the loaded data before and when i refresh the fragment, the fragment load new data. An example app like a twitter or facebook. What i have to do? thanks for reading</p>
<pre><code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View Vi = inflater.inflate(R.layout.list_kuliah, container, false);
//Hashmap for ListView
contactList = new ArrayList<HashMap<String, String>>();
progress = (LinearLayout) Vi.findViewById(R.id.linlaHeaderProgress);
ListView lv = (ListView) Vi.findViewById(R.id.list1);
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String email = ((TextView) view.findViewById(R.id.publisher))
.getText().toString();
String address = ((TextView) view.findViewById(R.id.description))
.getText().toString();
//String thumb_url = ((ImageView))
// Starting single contact activity
Intent in = new Intent(getActivity() ,SingleKuliahAct.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, email);
in.putExtra(TAG_ADDRESS, address);
startActivity(in);
getActivity().overridePendingTransition( R.anim.left1, R.anim.left2 );
}
});
new MyAsyncTask().execute();
return Vi;
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progress.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... args0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
//getting JSON string from URL
String jsonStr = sh.makeServiceCall(url_contacts, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_ADDRESS, address);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
/*ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_kuliah_item, new String[] { TAG_NAME, TAG_EMAIL, TAG_ADDRESS}, new int[] { R.id.title,
R.id.publisher, R.id.description });
ListView mView = (ListView)
getView().findViewById(R.id.list1);
mView.setAdapter(adapter);*/
KuliahAdapter adapter;
ListView List = (ListView) getView().findViewById(R.id.list1);
adapter = new KuliahAdapter(getActivity(), contactList);
List.setAdapter(adapter);
progress.setVisibility(View.GONE);
}
</code></pre>
<p>above is my code on fragment kuliah (fragment A), and i have adapter for each fragment</p>
<pre><code>public class KuliahAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public KuliahAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_kuliah_item, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.publisher); // artist name
TextView duration = (TextView)vi.findViewById(R.id.description); // duration
//TextView countcomment = (TextView)vi.findViewById(R.id.countcomment); // duration
//TextView countlikes = (TextView)vi.findViewById(R.id.countlikes); // duration
//TextView created = (TextView)vi.findViewById(R.id.created); // created
//ImageView thumb_image=(ImageView)vi.findViewById(R.id.image); // default image
HashMap<String, String> contactList = new HashMap<String, String>();
contactList = data.get(position);
// Setting all values in listview
title.setText(contactList.get(KuliahFragment.TAG_NAME));
artist.setText(contactList.get(KuliahFragment.TAG_EMAIL));
duration.setText(contactList.get(KuliahFragment.TAG_ADDRESS));
//countcomment.setText(courses.get(KuliahFragment.TAG_COUNTCOMMENT));
//countlikes.setText(courses.get(KuliahFragment.TAG_COUNTLIKES));
//created.setText(courses.get(KuliahFragment.TAG_CREATED));
//imageLoader.DisplayImage(courses.get(KuliahFragment.TAG_IMAGE), thumb_image);
return vi;
}
</code></pre>
<p>}</p>
| 3 | 2,751 |
Combining CSS Animations. What next?
|
<p>I am trying to make an animation of a stack of folders, where they will raise up, and then open to reveal the inside of the folder on hover (all but the bottom folder need to rise). </p>
<p>So far I have made the all top folders rise, and I've made the bottom folder open. Where I'm stuck is how to get the top folders to open after they rise. (side problem: getting both the front flap and the back of the folder to rise at the same time).</p>
<p>Here's a jsfiddle of what I have so far. Here to learn! Thanks</p>
<p><a href="https://jsfiddle.net/m4ax81r6/" rel="nofollow">https://jsfiddle.net/m4ax81r6/</a></p>
<p>Edit:
To add a little more clarification - the front and back of the folder need to rise together on hover of the front of the folder. Then the front of the folder needs to fold down, while all still risen. Last, the folder needs to fold back up and lower when the mouse stops hovering.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style>
.folder {
width: 500px;
height: 250px;
display: block;
transition: transform .5s;
transition-timing-function: ease-in-out;
position: relative
}
#folder1 {
z-index: 1;
}
#folder2 {
margin-top: -100px;
z-index: 2;
}
#folder3 {
margin-top: -100px;
z-index: 3;
bottom: 250px;
}
.movefolder:hover {
transform: translatey(-100px);
}
.front {
top: -105px;
width: 500px;
height: 240px;
display: block;
transition: transform .5s;
transition-timing-function: ease-in-out;
position: relative;
animation-delay: 2s;
transform-origin: bottom;
z-index: 4;
}
.openfolder:hover {
transform: rotateX(-85deg);
}
</style>
</head>
<body style="margin-left:50px; margin-top:100px; margin-bottom:50px;">
<img id="folder1" class="folder movefolder" src="https://s3.amazonaws.com/8z-marketing/8z+Mortgage/folder2-01.png" />
<img id="folder2" class="folder movefolder" src="https://s3.amazonaws.com/8z-marketing/8z+Mortgage/folder2-01.png" />
<img class="front openfolder" src="https://s3.amazonaws.com/8z-marketing/8z+Mortgage/front-folder-border-01.png" />
<img id="folder3" class="folder" src="https://s3.amazonaws.com/8z-marketing/8z+Mortgage/folder2-01.png" />
</body>
</html>
</code></pre>
| 3 | 1,258 |
what does this line do in this code?
|
<p>i have found following code on online for suffix tree</p>
<pre><code>#include <stdio.h>
#define E 0
struct suffix_tree_node;
struct suffix_tree_link {
// 0 is e - global index of during string's end
unsigned long start;
unsigned long end;
suffix_tree_link(suffix_tree_node* source, suffix_tree_node* target,
unsigned long start, unsigned long end) {
this->source = source;
this->target = target;
this->start = start;
this->end = end;
}
suffix_tree_node* source;
suffix_tree_node* target;
suffix_tree_link* next_link;
};
struct suffix_tree_node {
suffix_tree_link* first_link;
suffix_tree_node* parent_node;
suffix_tree_node* suffix_link_node;
// other constructors?
suffix_tree_node() {
parent_node = suffix_link_node = NULL;
first_link = NULL;
}
void add_target(unsigned long start, unsigned long end, suffix_tree_node* target) {
suffix_tree_link* link;
for(link = first_link; link != NULL; link = link->next_link);
link = new suffix_tree_link(this, target, start, end);
}
};
class suffix_tree {
suffix_tree_node* root;
const char* string;
void ukkonen() {
root->add_target(1, E, new suffix_tree_node);
unsigned long e = 1, j_i = 1, i = 1;
for( int i = 0; string[i] != '\0'; i++) {
e++;
for() {
j_star = j;
}
j_i = j_star;
}
}
public:
suffix_tree(const char* string) {
root = new suffix_tree_node();
this->string = string;
ukkonen();
}
};
int main() {
suffix_tree("foof");
return 0;
}
</code></pre>
<p>everything is clear almost in this code,because i have read about suffix tree many times before,but i did not understand this fragment:</p>
<pre><code>void ukkonen() {
root->add_target(1, E, new suffix_tree_node);
unsigned long e = 1, j_i = 1, i = 1;
for( int i = 0; string[i] != '\0'; i++) {
e++;
for() {
j_star = j;
}
j_i = j_star;
}
}
</code></pre>
<p>what does this code do?</p>
<p>also what is <code>for()</code>? or <code>j_start</code>?</p>
<p>here is <a href="https://github.com/qumon/da_labs/blob/a59083eac127aedf56b9fdfef27a0d63ce7af6bf/lab5.3.cpp" rel="nofollow">a link</a> for this code.</p>
| 3 | 1,216 |
Handling a Many-to-Many Dimension when all dimensional values have 100% importance
|
<p>I'll at least try to keep this succinct.</p>
<p>Let's suppose we're tracking the balances of accounts over time. So our fact table will have columns such as...</p>
<p><strong>Account Balance Fact Table</strong> </p>
<ul>
<li>(FK)AccountID </li>
<li>(FK)DateID</li>
<li>...</li>
<li>Balance</li>
<li>...</li>
</ul>
<p>Obviously you have an <strong>Account Dimension Table</strong> and a <strong>Date Dimension Table</strong>. So now we can easily filter on Accounts or Dates (or date ranges, etc.).</p>
<p>But here's the kicker... Accounts can belong to Groups -- any number of Groups at a given Date. Groups are simply logical abstractions, and they have no tangible meaning aside from reporting purposes. An Account being in 0, 1, or 17 groups doesn't affect its Balance in any way. For example, AccountID 1 may be in Groups 38, 76, 104, and 159. Account 2 may be in Group 1 (which has a Group Description of "Ungrouped". Account 3 may be in seventeen groups (real example).</p>
<p>As an added bonus, our users are completely non-technical. They don't know SQL, they have no experience with relational databases, and have historically done all of their work in a convoluted Excel solution. Right now we're building a dimensional model they can slice and filter with PowerPivot, though these Account Groups are threatening to turn an otherwise ruthlessly simple Star Schema into something complex enough that the users will balk and return to their current spaghetti solution.</p>
<p>So let's look at our options...</p>
<p><strong>Boolean Method</strong>
The Boolean method is not feasible. We have about 570,000 different accounts, but more importantly, 26,000 different groups. This would also be a devil for end-users to filter, since they're non-technical and are relying on very simple tools to get this done.</p>
<p><strong>Multiple Column Method</strong>
In theory this could work, however, we do have some accounts that belong to 17 groups. Again, the groups are really just logical groups -- they have no meaning, but they are required by the business for reporting purposes. Having end-users filter out groups from 17 different columns isn't going to go over well in user-acceptance, and would likely result in users refusing to use the solution (and I don't blame them).</p>
<p><strong>Bridge Table</strong>
This count work, but we do have 26,000 different groups. I'm not finding this to be user-friendly.</p>
<p>Since I'm not liking my options, I can only assume there's a better way other than snowflaking... unless snowflaking IS the only way. If someone could lend a hand and explain their rationale it'd be appreciated.</p>
<hr>
<p><strong>UPDATE:</strong> For clarification, an example I think everyone here can relate to is imagine you can list keyword skills on a resume. They all relate to the same person, but you can have any number of skills. The skills don't effect any of individual measures on a resume -- i.e. 'C++' isn't more valuable than 'C#' -- you can't put all the resume/skill combinations in the fact table or you'd end up double counting (or well more than double ;) ).</p>
<p>I think the best I'm going to be able to do here is to create an outrigger table for groups. I'm not a fan of it, but I think it's the only real option I have.</p>
<p>So now we have...</p>
<p><strong>Account Balance Fact Table</strong> </p>
<ul>
<li>(FK)AccountID </li>
<li>(FK)DateID</li>
<li>...</li>
<li>Balance</li>
<li>...</li>
</ul>
<p><strong>Account Dimension</strong></p>
<ul>
<li>(PK)AccountID</li>
<li>Account Name</li>
<li>...</li>
<li>(FK)Account Group Key</li>
</ul>
<p><strong>Account Group Outrigger</strong></p>
<ul>
<li>(PK)AccountGroupID</li>
<li>(PK)AccountID)</li>
<li>Account Group Name</li>
</ul>
| 3 | 1,088 |
Uploading a Image Works on some devices but returns Stream FixedLengthSource .inputStream()
|
<p>I am developing an android application that uploads an image to a specified directory using PHP and okhttp . Well , the frontend and backend work fine on my personal device , but it crashes on non-Samsung devices.</p>
<p>When I dug into the problem I found out that the server returns :</p>
<p>com.android.okhttp.internal.http.Http1xStream$FixedLengthSource@17768aa).inputStream()
on the non-Samsung devices.</p>
<p>The Java Code of the file Upload is as Follows :</p>
<pre><code>public class UploadGalleryStoryPost {
private Context context;
private String fileName = "", User_Id = "",Type="";
private ProgressDialog progressDialog;
private int serverResponseCode = 0;
private String count = "";
private String fileCount = "";
public UploadGalleryStoryPost(String fileName, Context context, String User_Id, String Type, String count, String fileCount) {
this.fileName = fileName;
this.context = context;
this.User_Id = User_Id;
this.Type = Type;
this.count = count;
this.fileCount = fileCount;
new UploadingGalleryPost().execute();
}
private class UploadingGalleryPost extends AsyncTask<Void, Void, Void> {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize =1024 * 1024;
File sourceFile_profile = new File(fileName);
private String upLoadServerUri = APP_SERVER_URL+"AddAStory.php";
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(context);
progressDialog.setMessage("Uploading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected void onPostExecute(Void result) {
try{
if(serverResponseCode == 200){
int count1 = Integer.parseInt(count);
int fileCount1 = Integer.parseInt(fileCount);
Log.e("value", " "+ String.valueOf(count1-1)+" "+fileCount1);
if((fileCount1-1) == count1) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context, R.style.myDialog);
builder1.setCancelable(false);
builder1.setTitle("Alert!");
builder1.setMessage("Uploaded successfully.");
builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent i = new Intent(context, DashBoard.class);
context.startActivity(i);
}
});
AlertDialog dialog1 = builder1.create();
dialog1.show();
}
else {
progressDialog.dismiss();
Toast.makeText(context, fileName+" has been uploaded successfully", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
Log.e("UploadtoserverException", "Exception : "
+ e.getMessage(), e);
}
super.onPostExecute(result);
}
@Override
protected Void doInBackground(Void... voids) {
try{
// open a URL connection to the Servlet
FileInputStream fileInputStream_profile = new FileInputStream(sourceFile_profile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
// conn.setChunkedStreamingMode(1024);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("Attachment", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"Attachment\";filename=\""+fileName+"\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream_profile.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream_profile.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream_profile.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream_profile.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"User_Id\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(User_Id);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"Type\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Type);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
conn.getErrorStream();
Log.e("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode+" "+ conn.getErrorStream());
//close the streams //
fileInputStream_profile.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
Log.e("UploadtoserverException", "Exception : "
+ e.getMessage(), e);
}
return null;
}
}
}
</code></pre>
<p>The php code is :</p>
<pre><code><?php
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$new_time = date("Y-m-d H:i:s", strtotime('+24 hours'));
$day = date("l");
$response = array();
include 'db_connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$User_Id = $_POST['User_Id'];
$Story_Content = $_POST['Story_Content'];
$B_Id = $_POST['B_Id'];
$Type = $_POST['Type'];
if($Type == 'BGTXT'){
$sql = "INSERT INTO Story_Common(User_Id,Timestamp_Start,Status, Timestamp_End)
VALUES('$User_Id','$date','Open','$new_time')";
$result = sqlsrv_query($conn, $sql);
if($result){
$sql1 = "SELECT TOP 1 * FROM Story_Common ORDER BY Story_Id DESC";
$res1 = sqlsrv_query($conn, $sql1);
if (sqlsrv_has_rows($res1) == true)
{
while ($row_sql1 = sqlsrv_fetch_array($res1, SQLSRV_FETCH_BOTH))
{
$Story_Id = $row_sql1["Story_Id"];
}
}
$sql2 = "INSERT INTO Story(Story_Id,Story_Content,B_Id)
VALUES('$Story_Id',N'$Story_Content','$B_Id')";
$result2 = sqlsrv_query($conn, $sql2);
if($result2){
$response['success'] = 200;
$response['message'] = "Insert in db success.";
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else if($Type == 'Photo/Video'){
$sql = "INSERT INTO Story_Common(User_Id,Timestamp_Start,Status,Timestamp_End)
VALUES('$User_Id','$date','Open','$new_time')";
$result = sqlsrv_query($conn, $sql);
if($result){
if (empty($_FILES["Attachment"]["name"])) {
$path = "NA";
}
else {
$Attachment=$_FILES["Attachment"]["name"];
$temp=$_FILES["Attachment"]["tmp_name"];
$tst= time();
$url = "Post_Media/" . $tst . $Attachment;
$path="http://kidsfb.kidsfb.com/ver1PHP/".$url;
move_uploaded_file($temp,$url);
}
$sql1 = "SELECT TOP 1 * FROM Story_Common ORDER BY Story_Id DESC";
$res1 = sqlsrv_query($conn, $sql1);
if (sqlsrv_has_rows($res1) == true)
{
while ($row_sql1 = sqlsrv_fetch_array($res1, SQLSRV_FETCH_BOTH))
{
$Story_Id = $row_sql1["Story_Id"];
}
}
$sql2 = "INSERT INTO Story_Media(Story_Id,Media_Att)
VALUES('$Story_Id','$path')";
$result2 = sqlsrv_query($conn, $sql2);
if($result2){
$response['success'] = 200;
$response['message'] = "Insert in db success.";
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
echo json_encode($response);
}
?>
</code></pre>
<p>Tried increasing the buffer size to 2048 from 1024 still doesn't work on other devices.</p>
| 3 | 5,910 |
Vertically merge dataframes
|
<p>I have a query regarding merging 4 dataframes
For example i have 4 dataframes as below :</p>
<pre><code>print(df1)
SET I Violations
Rule 1 1
Rule 2 1
Rule 3 6
print(df2)
SET II Violations
Rule 1 2
Rule 2 3
Rule 3 6
print(df3)
SET III Violations
Rule 1 2
Rule 2 4
Rule 3 8
print(df4)
SET IV Violations
Rule 1 2
Rule 2 5
Rule 3 8
</code></pre>
<p>My expected output :</p>
<pre><code>SET I Violations
Rule 1 1
Rule 2 1
Rule 3 6
SET II Violations
Rule 1 2
Rule 2 3
Rule 3 6
SET III Violations
Rule 1 2
Rule 2 4
Rule 3 8
SET IV Violations
Rule 1 2
Rule 2 5
Rule 3 8
</code></pre>
<p>Outputs i am getting right now :</p>
<p>a)</p>
<pre><code>SET I SET II SET III SET IV Violations
Rule 1 1
Rule 2 1
Rule 3 6
Rule 1 2
Rule 2 3
Rule 3 6
Rule 1 2
Rule 2 4
Rule 3 8
Rule 1 2
Rule 2 5
Rule 3 8
</code></pre>
<p>command_used:</p>
<pre><code>pandas.concat([df1,df2,df3,df4],axis=0,ignore_index=True)
</code></pre>
<p>b) </p>
<pre><code>Rule 1 1 Rule 1 2 Rule 1 2 Rule 1 2
Rule 2 1 Rule 2 3 Rule 2 4 Rule 2 5
Rule 3 6 Rule 3 6 Rule 3 8 Rule 3 8
</code></pre>
<p>command_used:</p>
<pre><code>pandas.concat([df1,df2,df3,df4],axis=1,ignore_index=True)
</code></pre>
<p>Please help me with above</p>
| 3 | 1,296 |
Normalize data for colormap
|
<p>I am plotting color for geopandas shape with 2 array data:</p>
<p>Here's my first array.</p>
<pre class="lang-py prettyprint-override"><code> newI =
array([ -467, -415, -414, -1001, -246, -147, -523, -327, -583,
-541, -290, -415, -453, -505, -791, -812, -672, -558,
-559, -1055, -327, -703, -419, -499, -273, -574, -802,
-450, -743, -221, -1282, -704, -352, -734, -430, -353,
-515, -1121, -664, -586, -171, -881, -402, -1024, -543,
-527, -384, -775, -931, -1380, -1662, -1069, -952, -435,
-1051, -921, -1211, -794, -547, -313, -511, -993, -430,
-262, -255, -675, -793, -1053, -702, -967, -1016, -230,
-405, -869, -689, -935, -190, -1473, -883, -1233, -240,
-607, -339, -1130, -909, -836, -667, -457, -847, -538,
-606, -457, -800, -322, -1339, -691, -627, -689, -365,
-600, -289, -810, -577, -187, -375, -574, -426, -662,
-695, -1003, -40, -1012, -279, -966, -587, -641, -753,
-461, -563, -604, -1013, -625, -506, -416, -1385, -459,
-760, -347, -308, -555, -325, -1588, -566, -533, -843,
-501, -448, -1022, -654, -602, -1201, -814, -754, -361,
-325, -1141, -725, -256, -601, -379, -496, -1099, -1101,
-598, -442, -773, -295, -1292, -558, -1234, -868, -1135,
-251, -1398, -453, -563, -1306, -693, -560, -512, -935,
-1168, -482, -431, -1199, -1249, -1199, -413, -1018, -194,
-375, -932, -1028, -436, -955, -463, -1303, -676, -554,
-601, -875, -661, -791, -443, -89, -879, -606, -577,
-475, -802, -734, -660, -684, -174, -902, -1241, -1320,
-575, -855, -222, -890, -701, -1082, -531, -693, -1008,
-1357, -433, -379, -192, -343, -477, -230, -938, -675,
-798, -259, -398, -778, -484, -817, -453, -564, -536,
-1599, -968, -547, -845, -1592, -256, -1139, -229, -926,
-474, -392, -990, -295, -558, -465, -497, -395, -468,
-310, -507, -1205, -705, -739, -609, -809, -610, -421,
-1057, -2023, -1105, -618, -466, -1291, -616, -620, -571,
-904, -383, -544, -688, -461, -769, -990, -664, -405,
-419, -852, -435, -298, -782, -758, -371, -813, -421,
-594, -259, -284, -215, -452, -430, -936, -994, -981,
-502, -510, -671, -721, -829, -523, -288, -653, -493,
-983, -1205, -722])
</code></pre>
<p>and Here's my second array:</p>
<pre class="lang-py prettyprint-override"><code> array([-2407, -1992, -3400, -4826, -1544, -820, -3120, -1469, -2869,
-3622, -1738, -2122, -2773, -2939, -3558, -3575, -3082, -2494,
-3591, -5022, -1619, -2608, -3371, -3054, -1596, -2538, -3566,
-2035, -3490, -522, -5362, -3055, -1517, -4107, -2039, -2497,
-2302, -5513, -3876, -4303, -831, -4457, -2027, -5083, -2716,
-2284, -1288, -3781, -4707, -6903, -8592, -5763, -4644, -1999,
-4894, -3190, -6263, -3484, -3090, -1899, -2640, -3940, -2919,
-629, -2018, -4228, -4075, -5249, -2794, -4061, -4089, -1500,
-2434, -3867, -3359, -4070, -1472, -7334, -4367, -5422, -1563,
-3092, -1803, -4664, -4096, -3875, -3061, -1181, -4098, -2850,
-4356, -2239, -3102, -1498, -6458, -3495, -2863, -3568, -1752,
-3422, -1768, -3675, -2061, -919, -1452, -2512, -1924, -3668,
-3931, -4348, -284, -6232, -1065, -4261, -2739, -3392, -3962,
-2369, -2508, -3156, -4759, -3012, -3345, -2566, -7910, -2215,
-3581, -1357, -2155, -2643, -1420, -7449, -3023, -2982, -4913,
-2835, -1748, -4679, -2950, -2951, -5515, -4195, -3568, -1746,
-1437, -5429, -3246, -1556, -2635, -1534, -3553, -4451, -5655,
-2616, -2724, -4445, -1642, -6640, -2869, -5211, -5014, -4909,
-1103, -5658, -2096, -2427, -5719, -3152, -2717, -2544, -4226,
-4813, -2319, -2261, -4844, -5383, -5057, -2981, -5448, -1526,
-1749, -3550, -3736, -1893, -5812, -2686, -5923, -3145, -3569,
-2523, -4586, -2931, -4104, -2301, -666, -4402, -3201, -3171,
-2598, -4279, -3765, -3024, -3085, -468, -3732, -5899, -6464,
-3993, -4583, -1126, -4193, -4214, -3902, -2132, -3712, -4879,
-6907, -1524, -1987, -1444, -2086, -3229, -1316, -4331, -3150,
-4449, -1700, -1486, -3650, -2478, -4166, -2618, -3308, -2458,
-7441, -4452, -2438, -4722, -6949, -1712, -4727, -792, -4193,
-1610, -1951, -3965, -1410, -2958, -2167, -2050, -2035, -2152,
-2236, -3235, -5999, -4024, -3111, -3196, -3881, -2647, -2579,
-6387, -9912, -4677, -2983, -1913, -7547, -3166, -2990, -2183,
-3401, -2080, -3056, -2225, -2546, -4421, -3867, -2975, -1552,
-2090, -3871, -1768, -2032, -3564, -3273, -1579, -4338, -1371,
-3600, -1253, -2083, -1439, -2281, -2045, -4406, -4380, -4129,
-2520, -2529, -2108, -3081, -3561, -2601, -843, -3069, -1852,
-5888, -5730, -3386])
</code></pre>
<p>The code to plot those array data is as shown below.</p>
<pre class="lang-py prettyprint-override"><code> area_gpd = gpd.read_file("....shp")
area_gpd['population'] = newI
plt.rcParams.update({'font.size':32})
west,south,east,north = area.unary_union.bounds
fig,ax = plt.subplots(figsize=(40,40))
cmap = LinearSegmentedColormap.from_list('mycmap', [ 'green','white'])
melbourne_gpd.plot(ax=ax, column='population',legend=False,cmap=cmap,zorder=3)
sm = plt.cm.ScalarMappable(cmap=cmap,\
norm=plt.Normalize(vmin=-9912,
vmax=-284))
</code></pre>
<p>It keeps normalizing things so the intensity shows now different.
Is there any function to normalize this data?
I want the map to be darker for those with a larger value. Can anyone give me some recommendations?</p>
<p>Thanks so much</p>
| 3 | 3,494 |
Loop to get model fields, create new model instances based on API returned values
|
<p>I'm using a couple of different API calls to populate (create_or_update) a particular Model's fields. Instead of having to create a new series of create_or_update fields for every API call, I am trying to make a loop to get rid of boilerplate code. There is a small caveat in the fact that some of the fields returned by the api overlap with python reserved keywords (eg id, type). I need to be able to pick those out and rename them in the dict during the looping comparison.</p>
<ol>
<li>Looks up the Model and gets its fields, creating a list of those fields eg:</li>
</ol>
<pre><code>['id', 'organizationId', 'name', ... ]
</code></pre>
<ol start="2">
<li>Cycles through the API response and creates a dictionary of key:values for each response object. If the list value is found in the dictionary, set the key: value to what is found in the API response, otherwise, set the value for the field to None. </li>
</ol>
<pre><code>{ 'id': 'N_543265', 'organizationId': '43675', *name field missing* , ...}
</code></pre>
<p>Since both 'id' and 'organizationId' are found, I want their values to be updated into the Model instance, but as 'name' is not found, I want that to be skipped</p>
<p>The main issue I am having is that when this runs (it is a celery task), it tells me the following:</p>
<blockquote>
<p>database.models.Network.DoesNotExist: Network matching query does not exist.</p>
</blockquote>
<p><strong>models.py</strong></p>
<pre class="lang-py prettyprint-override"><code>class Device(models.Model):
networkId = models.ForeignKey(Network, on_delete=models.CASCADE, blank=True, null=True, related_name='network_device')
name = models.CharField(max_length=100, default='', blank=True, null=True)
organizationId = models.CharField(max_length=100, default='', blank=True)
</code></pre>
<p><strong>devices_status.py</strong></p>
<pre><code>...**API call happens here**
result = response.text
job = json.loads(result)
l = []
s = []
x = Device._meta.get_fields()
for f in x:
fields = []
try:
l.append(str(f).split('.'))
for a in l:
s.append(a[-1])
for q in s:
if '<' in q:
continue
elif '>' in q:
continue
else:
fields.append(q)
except AttributeError as e:
print(e)
pass
for line in job:
d = {}
for k, v in line.items():
if k in fields:
d[k] = v
else:
continue
# Have to delete this from the auto field pull otherwise it gets
# confused with python factory vars
try:
del d['type']
except KeyError as e:
print('Delete type: {}'.format(e))
pass
try:
Device.objects.update_or_create(
networkId = Network.objects.get(networkId=d['networkId']),
name = d['name'],
serial = d['organizationId'],
defaults = d
)
except KeyError as e:
print(e)
pass
return result
</code></pre>
<p>Basically, I want my model instance to populate based on comparing fields returned in the API, to avoid throwing a KeyError, and without having a long list of try/except to manually fish out fields that may or may not exist in the API data. </p>
<p>Any assistance would be great, even if it is more high level about the way I've gone about the problem. I think a lot of people could gain from this snippet if i can get it working correctly.</p>
<p><strong><em>EDIT</em></strong></p>
<p>I managed to find a solution to this problem, so I have detailed it here for anyone interested. I have found this solution saves me a lot of headaches when importing data to the database from an API with varying fields.</p>
<p>I will use a shortened version of data returned from the Meraki dashboard API (<a href="https://dashboard.meraki.com/api_docs" rel="nofollow noreferrer">https://dashboard.meraki.com/api_docs</a>):</p>
<pre><code>...**API returned data**
[
{
"lat": 1.0,
"lng": 1.0,
"address": "123 fake street",
"serial": "2222-2222-2222",
"mac": "22:22:22:22:22:22",
"lanIp": "10.1.1.2",
"tags": "tag1 tag2",
"networkId": "5678",
"name": "accesspoint01",
"model": "ap01"
},
{
"lat": 2.0,
"lng": 2.0,
"address": "123 fake street",
"serial": "5555-5555-5555",
"mac": "44:44:44:44:44:44",
"wan1Ip": "1.1.1.1",
"wan2Ip": null,
"lanIp": "10.10.10.10",
"networkId": "2468",
"name": "gateway01",
"model": "gw01"
},
]
...
</code></pre>
<p>This is the type of API data we will expect to process and add into the database.</p>
<p><strong>models.py</strong></p>
<pre class="lang-py prettyprint-override"><code>class Device(models.Model):
# FK
parent_network = models.ForeignKey(Network, on_delete=models.CASCADE, blank=True, null=True, related_name='network_device')
name = models.CharField(max_length=100, default='', blank=True, null=True)
lat = models.CharField(max_length=100, default='', blank=True, null=True)
lng = models.CharField(max_length=100, default='', blank=True, null=True)
tags = models.CharField(max_length=200, default='', blank=True, null=True)
serial = models.CharField(max_length=100, default='', blank=True, null=True)
mac = models.CharField(max_length=100, default='', blank=True, null=True)
publicIp = models.CharField(max_length=100, default='', blank=True, null=True)
lanIp = models.CharField(max_length=100, default='', blank=True, null=True)
wan1Ip = models.CharField(max_length=25, default='', blank=True, null=True)
wan2Ip = models.CharField(max_length=25, default='', blank=True, null=True)
model = models.CharField(max_length=100, default='', blank=True, null=True)
address = models.CharField(max_length=100, default='', blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created')
updated_at = models.DateTimeField(auto_now=True, verbose_name='Last Updated')
def __str__(self):
return str(self.name)
class Meta:
ordering = ['name']
</code></pre>
<p><strong>device.py</strong> (I have several similar functions in a folder, named after their function for ease of management)</p>
<pre class="lang-py prettyprint-override"><code>def device(apikey):
excludes = ['serial', 'parent_network']
## Once the request has been made, the returned data is assigned
...
response = requests.request("GET", url, headers=headers)
result = response.text
job = json.loads(result)
# Create the dictionary that will be used in defaults of update_or_create
d = {}
# Iterate over the key:value items returned from the API call
for k, v in job.items():
try:
# This part checks the keys in the returned dataset to create dictionary entries based on those returned values
if k in excludes:
continue
else:
d[k] = v
d['parent_network'] = Network.objects.get(parent_network=job['networkId'])
except Exception as e:
print('[*] device.py - Dictionary error: {}'.format(e))
continue
# Add the object to the database, based on the serial we return from the API
try:
Device.objects.update_or_create(
serial=job['serial'],
defaults=d,
)
except KeyError as e:
print('[*] device.py - Device KeyError: {}'.format(e))
pass
</code></pre>
<p>Why have an array excluding some items from the dictionary???</p>
<p><strong>'serial'</strong> - Excluded because we want to use this as our unique field to search for an object to update
<strong>'parent_network'</strong> - This is a foreign key field, so this has to be fed a 'Network' object</p>
<p>Now if we have other similar functions that have to deal with API data, we have a
bit of a template that we can copy. All we need to do to apply it to a new
set of API data is change the 'excludes' array and process any ForeignKey fields
outside of the k, v loop.</p>
<p>The next thing to do would be to turn this into a fully re-usable vanilla function
that can be passed all the required variables but unfortunately, that is out of my
range of skills. It would be great to see someone else do this if possible.</p>
<p>I hope this has been helpful. <em>Thanks for reading!</em></p>
| 3 | 3,379 |
The samples read from the AVAssetReader is not in order
|
<p>I have a trouble while reading the sample buffers from a file using AVAssetreader. The timestamps of the samples read seem to be out of order. Is this the expected result or is there something I am doing wrong. Below is the reading and writing code I am using -</p>
<pre><code>[assetWriterInput requestMediaDataWhenReadyOnQueue:serializationQueue usingBlock:^{
if (finished)
return;
BOOL completedOrFailed = NO;
// Read samples in a loop as long as the asset writer input is ready
while ([assetWriterInput isReadyForMoreMediaData] && !completedOrFailed)
{
CMSampleBufferRef sampleBuffer = [assetReaderOutput copyNextSampleBuffer];
CMTime originalTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
if (sampleBuffer != NULL)
{
CMTime cmm1 = CMSampleBufferGetOutputDuration(sampleBuffer);
NSLog(@"Timestamps == %f",time);
CMSampleBufferRef newSampleBuffer;
CMSampleTimingInfo sampleTimingInfo;
sampleTimingInfo.duration = cmm1;
float milliseconds = videoPTM * 600;
sampleTimingInfo.presentationTimeStamp = CMTimeMake((int)milliseconds, 600);
sampleTimingInfo.decodeTimeStamp = kCMTimeInvalid;
CMSampleBufferCreateCopyWithNewTiming(kCFAllocatorDefault,
sampleBuffer,
1,
&sampleTimingInfo,
&newSampleBuffer);
BOOL success = YES;
success = [assetWriterInput appendSampleBuffer:newSampleBuffer];
CFRelease(newSampleBuffer);
newSampleBuffer = NULL;
CFRelease(sampleBuffer);
sampleBuffer = NULL;
completedOrFailed = !success;
videoPTM+=CMTimeGetSeconds(cmm1);
}
else
{
completedOrFailed = YES;
}
}
if (completedOrFailed)
[self callCompletionHandlerIfNecessary];
</code></pre>
<p>When I print the timestamps of the samples read they are not in order like this...</p>
<pre><code> Video Timestamps == 6.971667
Video Timestamps == 7.055000
Video Timestamps == 7.220000
Video Timestamps == 7.136667
Video Timestamps == 7.386667
Video Timestamps == 7.303333
Video Timestamps == 7.470000
Video Timestamps == 7.635000
</code></pre>
<p>Please let me know the reason of the same and how I can create a copy of the samples with a different presentation time.</p>
| 3 | 1,232 |
create another instance 'B' after saving an instance 'A' automatically
|
<p>i'm using <code>Django 1.7</code> with <code>django_rest_framework 3.0</code> to develop a restful backend for my application.</p>
<p><strong><em>The scenario:</em></strong> On the client the user will authenticate with a social network, say facebook. The <code>token</code> is sent back to the server which creates and stores an instance of <code>Social</code> model. </p>
<p><strong><em>The need:</em></strong> On saving the <code>Social</code> model, I want to <em>automatically</em> create and store an instance of <code>django.contrib.auth.models User</code> model. The data for the <code>User</code> model will be extracted from the social network that the user just authenticated with.</p>
<p><strong><em>My approach #1:</em></strong> Is there some way where I can send a combined json request to my django backend and create independent <code>User</code> and <code>Social</code> instances. I think this would require changing the <code>serializers.py</code> (given below) code. </p>
<p>For example (request sent to my django):</p>
<pre><code>{
'social':{
'token':'XYZ',
'source':'FB',
},
'user_details':{
'first_name':'sahil',
'last_name':'gandhi',
'username':'sahilgandhi',
'email':'sa***com',
'password':'password',
'date_of_birth':'01/01/2015'
}
}
</code></pre>
<p><strong><em>My approach #2:</em></strong> I stumbled across a <code>post_save()</code> signal in django's framework. this is my code implementing the post_save() method
This doesn't require a combined request like <strong>approach #1</strong> but a simple post request that will be handled by <code>SocialSerializer</code></p>
<pre><code>@receiver(post_save, sender=Social)
def create_user_after_social_signup(sender, instance, created=False, **kwargs):
"""
Automatically create a User instance for every Social signup
:param sender: Social model
:param instance: Social instance that just got created
:param created: is new instance created; boolean
:param kwargs:
:return:
"""
if created:
social = Social.objects.get(pk=instance.id)
# get user details from social (ex: facebook)
payload={'access_token':social.token}
url='https://graph.facebook.com/v2.2/me'
r=requests.get(url, params=payload)
# create user from response using:
# User.objects.create_superuser()
</code></pre>
<p>How to do this if facebook's response is this?</p>
<pre><code> {
"id": "XYZ",
"birthday": "0***4",
"email": "sahi***@gmail.com",
"first_name": "Sahil",
"gender": "male",
"last_name": "Gandhi",
"link": "https://www.facebook.com/app_sco*******632440/",
"location": {
"id": "1*****2",
"name": "M*******a"
},
"locale": "en_US",
"name": "Sahil Gandhi",
"timezone": 5.5,
"updated_time": "2015****00",
"verified": true
}
</code></pre>
<p>My current code is as follows:</p>
<p><strong>models.py</strong></p>
<pre><code>class Social(models.Model):
NONE = 'XX'
FACEBOOK = 'FB'
GOOGLEPLUS = 'GP'
TWITTER = 'TW'
LINKEDIN = 'LI'
SOCIAL_NETWORKS = (
(NONE, '------'),
(FACEBOOK, 'Facebook'),
(TWITTER, 'Twitter'),
(GOOGLEPLUS, 'Google Plus'),
(LINKEDIN, 'LinkedIn'),
)
user = models.OneToOneField(User, related_name='social_owner')
token = models.CharField(max_length=250)
# expires_at = models.DateTimeField('token expires at', blank=True, null=True)
source = models.CharField(max_length=2, choices=SOCIAL_NETWORKS,)
class Meta:
db_table = 'user_social'
</code></pre>
<p><strong>serializer.py</strong></p>
<pre><code>class SocialSerializer(serializers.ModelSerializer):
class Meta:
model = Social
fields = ('user', 'token', 'source')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('pk', 'first_name', 'last_name', 'username', 'email', 'date_joined')
</code></pre>
<p><strong>views.py</strong> normal class based view, i.e. <code>APIView</code> for the models: <code>User</code> and <code>Social</code>.</p>
<p><strong><em>Finally:</em></strong>
I strongly feel that the <strong><em>approach #1</em></strong> is the better way to do it. Just don't know how to go about it. Either way your help is appreciated. </p>
| 3 | 1,487 |
jQuery form submission handler - odd behaviour
|
<p>Edit: answered, was a syntax error, see below for fixed code...</p>
<p>Hi all, long time reader, first time asker.</p>
<p>The below code is <em>always</em> allowing form submission, even given that I've overidden the return value at the end of the function, outside of any conditional statements. Form submission is only disallowed if there is NOTHING in the function body except return false. Deeply odd.</p>
<p>I have verified that the function is being called on form submission by entering an alert in the function body and checking that it alerts me. I tried stripping the code out into a discrete function and specifying that as the event handler, no difference.</p>
<p>The workaround is probably to monitor the state of my controls and disable/enable the submit button of the form accordingly, but surely I'm just missing something obvious as this technique works everywhere else.</p>
<p>Does anyone have any ideas? My google-fu has failed me and SO doesn't have anything on this that I could see (yet). I'm at my wit's end. The context for this, btw, is FF3, jQuery 1.4.2, and I'm working on my company's mantisbt installation. The html of the form is completely normal.</p>
<p>Cheers,</p>
<p>G</p>
<pre><code> jQuery(document.forms[2]).submit(function(){
var canSubmit = true;
var msg = '';
// we only do validation if those controls are present and have some options which can be selected
if(jQuery("select[name=priority] option").length() > 0 && jQuery("select[name=severity] option").length() > 0){
//there must be a selection in priority
if(jQuery("select[name=priority]").val() == ''){
canSubmit = false;
msg = msg + 'Please select a priority!\n';
}
//there must be a selection in severity
if(jQuery("select[name=severity]").val() == ''){
canSubmit = false;
msg = msg + 'Please select a severity!\n';
}
//the priority cannot be P1 or P2 and also a feature request
if( jQuery("select[name=priority]").val() > 49
&& jQuery("select[name=severity]").val() == 60){
canSubmit = false;
msg = msg + 'Feature requests cannot be P1 or P2!';
}
//if there is some feedback, alert it to the user
if(msg != ''){
alert(msg);
}
}
//debugging override - always return false!
return false; //instead of canSubmit;
});
</code></pre>
<p>Edit: here's the fixed code. Many thanks Gaby!</p>
<pre><code> var canSubmit = true;
var msg = '';
// validate form submission
jQuery(document.forms[2]).submit(function(e){
msg = '';
canSubmit = true;
// we only do validation if those controls are present and have some
// options
// which can be selected
if(jQuery("select[name=priority] option").length > 0 &&
jQuery("select[name=severity] option").length > 0){
// there must be a selection in priority
if(jQuery("select[name=priority]").val() == 0){
canSubmit = false;
msg = msg + 'Please select a priority!\n';
}
// there must be a selection in severity
if(jQuery("select[name=severity]").val() == 0){
canSubmit = false;
msg = msg + 'Please select a severity!\n';
}
// the priority cannot be P1 or P2 and also a feature request
if( jQuery("select[name=priority]").val() > 49
&& jQuery("select[name=severity]").val() == 60){
canSubmit = false;
msg = msg + 'Feature requests cannot be P1 or P2!';
}
if(!canSubmit){
// if there is some feedback, alert it to the user
if(msg != ''){
alert("There were some problems:\n" + msg);
}
return false;
}
}
});
</code></pre>
| 3 | 1,537 |
Fetching different data from the same query in GraphQL
|
<p>For background, we're using HotChocolate in C#, with Apollo Angular and graphql-codegen.</p>
<p>We want to fetch some data from a query, but twice within one named query with different criteria, for instance:</p>
<pre><code>
query getTeamMembers($organisationId: UUID!, $cursor: String) {
teamMembers(organisationId: $organisationId, after: $cursor) {
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
edges {
cursor
node {
...teamMember
}
}
totalCount
}
teamMembersWithSpecificCriteria: teamMembers(organisationId: $organisationId, after: $cursor, where: {...}
] }}) {
totalCount
}
}
</code></pre>
<p>As you can see, this query (<code>getTeamMembers</code>) will fetch data from the same query resolver (<code>teamMembers</code>), but one is the entire dataset, the other is a subset of that data with a where clause.</p>
<p>(I've had to blur/change some names for reasons).</p>
<p>This seemingly <em>works</em> in the network request:</p>
<p><a href="https://i.stack.imgur.com/KzNtr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KzNtr.png" alt="Network request" /></a></p>
<p>but as you can see, both results have the same <code>__typename</code>, causing Apollo Angular to overwrite the data and set <code>23</code> for both:</p>
<p><a href="https://i.stack.imgur.com/o2V80.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o2V80.png" alt="enter image description here" /></a></p>
<p>The code we have looks like this:</p>
<pre class="lang-js prettyprint-override"><code>
this.teamMembersQuery = this.apollo.watchQuery<GetTeamMembersQuery,
GetTeamMembersQueryVariables>({
query: GetTeamMembersDocument,
fetchPolicy: "cache-and-network",
variables: {
organisationId: currentOrganisation?.id
}
});
this.teamMembers$ = this.teamMembersQuery.valueChanges.pipe(
map((result) => {
this.cursor = result.data.teamMembers?.pageInfo.endCursor;
this.hasNextPage = result.data.teamMembers?.pageInfo.hasNextPage;
this.totalTeamMembersCount = result.data.teamMembers?.totalCount ?? 0;
this.totalSpecificTeamMembersCount = result.data.teamMembersWithSpecificCriteria?.totalCount ?? 0;
return result.data.teamMembers?.edges?.map((e) => e.node) ?? [];
})
);
</code></pre>
<p>Is there a way around this without having to create another query resolver on the server? Isn't this the entire point of GraphQL to be able to query different data like this?</p>
<p>Any tips would be entirely helpful.</p>
| 3 | 1,109 |
Efficient controlled random walks in gremlin
|
<h2>Goal</h2>
<p>The objective is to efficiently generate random walks on a relatively large graph with uneven probabilities of going through edges depending on their type.</p>
<h2>Configuration</h2>
<ul>
<li>Ubuntu VM, 23Go RAM</li>
<li>JanusGraph 0.6.1 full</li>
<li>Local graph (default <code>conf/remote.yaml</code> file used)</li>
<li>~1.8m vertices (~28k will be start nodes for the random walks)</li>
<li>~21m relationships (they can all be used in the random walks)</li>
</ul>
<h2>What I am doing</h2>
<p>I am currently generating random walks with the <code>sample</code> command:</p>
<pre><code>g.V(<startnode_id>).
repeat( local( both().sample(1) ) ).
times(<desired_randomwalk_length>).
path()
</code></pre>
<h2>What I tried</h2>
<p>I tried using a gremlinpython script to create a random walk generator that would first get all edges connected to the current node, then pick randomly an edge to go through and repeat <code><desired_randomwalk_length></code> times.</p>
<pre class="lang-py prettyprint-override"><code>from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.structure.graph import Vertex
from typing import List
connection = DriverRemoteConnection(<URL>, "g")
g = traversal().withRemote(connection)
def get_next_node(start:Vertex) -> Vertex:
next_vertices = g.V(start.id).both().fold().next()
return next_vertices[randint(0, len(next_vertices)-1)]
def get_random_walk(start:Vertex, length:int=10) -> List[Vertex]:
current_node = start
random_walk = [current_node]
for _ in range(length):
current_node = get_next_node(current_node)
random_walk.append(current_node)
return random_walk
</code></pre>
<h2>Issues</h2>
<p>While testing on a subset of the total graph (400k vertices, 1.5m rel), I got these results</p>
<ul>
<li>Sample query, <code><desired_randomwalk_length></code> of 10: 100k random walks in 1h10</li>
<li>Gremlinpython function, <code><desired_randomwalk_length></code> of 4: 2k random walks in 1h+</li>
</ul>
<p>The sample command is really fast, but there are a few problems:</p>
<ol>
<li>It doesn't seem to truly be a uniform distribution pick amongst the edges (<a href="https://kelvinlawrence.net/book/Gremlin-Graph-Guide.html#_using_math_random_to_more_randomly_select_a_single_vertex" rel="nofollow noreferrer">it seems to be successive coin tosses</a>) which could lead to certain paths being taken more often, which then diminishes the interest of generating random walks. (I can't directly do what is recommended here as the nodes ids aren't in a sequence, thus I have to acquire them first.)</li>
<li>I haven't found a way to give different probabilities to different types of relationships.</li>
</ol>
<p>Is there a better way to do random walks with Gremlin?<br />
If there is none, is there a way to modify the sample query to rectify the assign probabilities to types of edges? Maybe even a way to have a better distribution of the sampling?<br />
In last recourse, is there a way to improve the queries to make this "by hand" with a gremlinpython script?</p>
<p>Thanks to everyone reading/replying!</p>
<h2>EDIT</h2>
<p>Is there a way to do the following:</p>
<ul>
<li>Given a <code>r_type1</code>, <code>r_type2</code>, <code>r_type3</code>, ... the acceptable relationship type for this random walk</li>
<li>Given a <code>proba1</code>, <code>proba2</code>, <code>proba3</code>, ... the probabilities of going through these relationship types</li>
</ul>
<p>For each step</p>
<ol>
<li>Sample a node for each relationship type <code>r_type1</code>, <code>r_type2</code>, <code>r_type3</code>, ...</li>
<li>Keep only one according to the probabilities <code>proba1</code>, <code>proba2</code>, <code>proba3</code>, ...</li>
</ol>
<p>I think the second step could be done be sampling multiple nodes for each relationships, in accordance with the probas (which could be done by using a <code>gremlinpython</code> script to build the query). This still leaves the question of how to sample on multiple relationships from a single node, and how to randomly pick one in the sampled nodes.</p>
<p>I hope this is clear!</p>
| 3 | 1,373 |
How to create login endpoint for serverless app with aws cognito service?
|
<p>I need to create login endpoint using cognito and serverless framework, i already created signUP and confirm email endpoints, but whatever i do with logIn endpoint i get error <code>"message": "Internal server error"</code>. I try everything but still get this error. Help me, please.</p>
<p>This is my login endpoind code:</p>
<h1>userSignIn.js</h1>
<pre><code>'use strict'
const Responses = require('../common/api_responses');
const AWS = require('aws-sdk');
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});
const cognitoUserPoolClient = process.env.cognitoUserPoolClient
exports.handler = function(event, context, callback){
const user_data = JSON.parse(event.body);
var params = {
'AuthFlow': 'ADMIN_NO_SRP_AUTH',
"AuthParameters":{
"USERNAME": user_data.email,
"PASSWORD": user_data.password
},
"ClientId": 'xxxxxxxxxxxxxxxxxxxxx',
"UserPoolId": 'us-east-1_XXXXXXX'
};
cognitoidentityserviceprovider.adminInitiateAuth(params, function(err, data) {
if (err) {
return Responses._400({err});
}
else{
callback(null, Responses._200({data}));
}
});
};
</code></pre>
<p>Config file :</p>
<h1>serverless.yml</h1>
<pre><code>provider:
name: aws
runtime: nodejs12.x
lambdaHashingVersion: 20201221
profile: testSLSBlogApi
region: us-east-1
stage: dev
environment:
tableNamePost: ${self:custom.tableNamePost}
imageUploadBucket: ${self:custom.imagePostsBucket}
region: ${self:provider.region}
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:*
- s3:*
- ses:*
Resource: '*'
functions:
userSignUp:
handler: lambdas/endpoints/userSignUp.handler
events:
- http:
path: sign-up
method: POST
cors: true
confirmSignUp:
handler: lambdas/endpoints/confirmSignUp.handler
events:
- http:
path: confirm-email
method: POST
cors: true
userSignIn:
handler: lambdas/endpoints/userSignIn.handler
events:
- http:
path: sign-in
method: POST
cors: true
resources:
Resources:
ImagesPostBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: ${self:custom.imagePostsBucket}
MyDynamoDBTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: ${self:custom.tableNamePost}
AttributeDefinitions:
- AttributeName: ID
AttributeType: S
KeySchema:
- AttributeName: ID
KeyType: HASH
BillingMode: PAY_PER_REQUEST
CognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: ${self:provider.stage}-user-pool
UsernameAttributes:
- email
AutoVerifiedAttributes:
- email
Policies:
PasswordPolicy:
MinimumLength: 6
RequireLowercase: False
RequireNumbers: True
RequireSymbols: False
RequireUppercase: True
CognitoUserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
ClientName: ${self:provider.stage}-user-pool-client
UserPoolId:
Ref: CognitoUserPool
ExplicitAuthFlows:
- ADMIN_NO_SRP_AUTH
GenerateSecret: false
</code></pre>
<p>This object i use for returning responses from lambdas handlers:</p>
<h1>api_responses.js</h1>
<pre><code>const Responses = {
_200(data = {}){
return {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Origin': '*',
},
statusCode: 200,
body: JSON.stringify(data),
};
},
_400(data = {}){
return {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Origin': '*',
},
statusCode: 400,
body: JSON.stringify(data),
};
},
};
module.exports = Responses;
</code></pre>
| 3 | 1,825 |
class variable reference problem in pygame little game
|
<p>i am self learning pygame, so with help of tutorials i have created following little game :</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from pygame.locals import *
from pygame import mixer
from os import path
import pickle
import pygame
pygame.mixer.pre_init(44100,-16,2,512)
mixer.init()
pygame.init()
screen_width =800
screen_height =800
screen =pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Platformer")
sky_img =pygame.image.load("sky.png")
sun_img =pygame.image.load("sun.png")
restart_img =pygame.image.load("restart_btn.png")
start_image =pygame.image.load("start_btn.png")
exit_image =pygame.image.load("exit_btn.png")
clock =pygame.time.Clock()
pygame.mixer.music.load("music.wav")
pygame.mixer.music.play(-1,0.0,5000)
fps =60
tile_size =40
score= 0
white=(255,255,255)
blue =(0,0,255)
font =pygame.font.SysFont('Bauhaus 93',70)
font_score =pygame.font.SysFont('Bauhaus 93',30)
#pickle_in =open("level7_data",'rb')
#world_data =pickle.load(pickle_in)
coin_fx = pygame.mixer.Sound('coin.wav')
coin_fx.set_volume(0.5)
jump_fx = pygame.mixer.Sound('jump.wav')
jump_fx.set_volume(0.5)
game_over_fx = pygame.mixer.Sound('game_over.wav')
game_over_fx.set_volume(0.5)
def draw_text(text,font,text_col,x,y):
img =font.render(text,True,text_col)
screen.blit(img,(x,y))
def reset_level(level):
player.reset(100,screen_height-100)
platform_group.empty()
blob_group.empty()
lava_group.empty()
exit_group.empty()
if path.exists(f'level{level}_data'):
pickle_in =open(f'level{level}_data','rb')
world_data =pickle.load(pickle_in)
world =World(world_data)
return world
blob_group = pygame.sprite.Group()
lava_group =pygame.sprite.Group()
exit_group =pygame.sprite.Group()
coin_group = pygame.sprite.Group()
game_over =0
main_menu =True
level =0
max_levels =7
class Exit(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
ex_image =pygame.image.load('exit.png')
self.image =pygame.transform.scale(ex_image,(tile_size,int(tile_size*1.5)))
self.rect =self.image.get_rect()
self.rect.x =x
self.rect.y =y
class World():
def __init__(self,data):
self.tile_list =[]
wall_imag =pygame.image.load("dirt.png")
grass_img =pygame.image.load("grass.png")
row_count =0
for row in data:
col_count =0
for tile in row:
if tile ==1:
img =pygame.transform.scale(wall_imag,(tile_size,tile_size))
img_rect =img.get_rect()
img_rect.x =col_count*tile_size
img_rect.y =row_count*tile_size
tile =(img,img_rect)
self.tile_list.append(tile)
if tile == 2:
img = pygame.transform.scale(grass_img, (tile_size, tile_size))
img_rect = img.get_rect()
img_rect.x = col_count * tile_size
img_rect.y = row_count * tile_size
tile = (img, img_rect)
self.tile_list.append(tile)
if tile ==3:
blob =Enemy(col_count*tile_size,row_count*tile_size+15)
blob_group.add(blob)
if tile == 4:
platform = Platform(col_count * tile_size, row_count * tile_size, 1, 0)
platform_group.add(platform)
if tile == 5:
platform = Platform(col_count * tile_size, row_count * tile_size, 0, 1)
platform_group.add(platform)
if tile ==6:
lava =Lava(col_count*tile_size,row_count*tile_size+(tile_size)//2)
lava_group.add(lava)
if tile==7:
coin =Coin(col_count*tile_size+(tile_size//2),row_count*tile_size+(tile_size//2))
coin_group.add(coin)
if tile==8:
exit =Exit(col_count*tile_size,row_count*tile_size-(tile_size)//2)
exit_group.add(exit)
col_count+=1
row_count+=1
def draw(self):
for tile in self.tile_list:
screen.blit(tile[0],tile[1])
class Button():
def __init__(self,x,y,image):
self.image =image
self.rect =self.image.get_rect(center = (x, y))
#self.x =x
#self.y =y
self.clicked =False
def draw(self):
action =False
pos =pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
if pygame.mouse.get_pressed()[0]==1 and self.clicked==False:
action =True
self.clicked =True
if pygame.mouse.get_pressed()[0] ==0:
self.clicked =False
screen.blit(self.image,self.rect)
return action
class Platform(pygame.sprite.Sprite):
def __init__(self,x,y,move_x,move_y):
pygame.sprite.Sprite.__init__(self)
platform_image =pygame.image.load("platform.png")
self.image =pygame.transform.scale(platform_image,(tile_size,tile_size//2))
self.rect =self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.move_counter = 0
self.move_direction = 1
self.move_x = move_x
self.move_y = move_y
def update(self):
self.rect.x+=self.move_direction*self.move_x
self.rect.y+=self.move_direction*self.move_y
self.move_counter+=1
if abs(self.move_counter)>50:
self.move_direction*=-1
self.move_counter*=-1
class Player():
def __init__(self,x,y):
self.reset(x,y)
def reset(self,x,y):
self.images_right = []
self.images_left = []
self.index = 0
self.counter = 0
for num in range(1, 5):
player_img = pygame.image.load(f'guy{num}.png')
player_img = pygame.transform.scale(player_img, (40, 80))
player_imag_Left = pygame.transform.flip(player_img, True, False)
self.images_right.append(player_img)
self.images_left.append(player_imag_Left)
self.dead_image = pygame.image.load('ghost.png')
self.image = self.images_right[self.index]
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.vel_y = 0
self.width = self.image.get_width()
self.height = self.image.get_height()
self.jumped = False
self.direction = 0
self.in_air =True
def update(self,game_over):
dx = 0
dy =0
walk_cooldown =5
col_thresh = 20
if game_over==0:
key =pygame.key.get_pressed()
if key[pygame.K_SPACE] and self.jumped ==False and self.in_air==False:
jump_fx.play()
self.vel_y =-15
self.jumped =True
if key[pygame.K_SPACE] == False:
self.jumped = False
if key[pygame.K_LEFT] ==True:
dx -=5
self.counter+=1
self.direction =-1
if key[pygame.K_RIGHT] ==True:
dx +=5
self.counter += 1
self.direction=1
if key[pygame.K_LEFT]==False and key[pygame.K_RIGHT]==False:
self.counter =0
self.index =0
if self.direction==1:
self.image =self.images_right[self.index]
if self.direction==-1:
self.image = self.images_left[self.index]
if self.counter >walk_cooldown:
self.counter =0
self.index+=1
if self.index>=len(self.images_right):
self.index =0
if self.direction==1:
self.image =self.images_right[self.index]
if self.direction==-1:
self.image = self.images_left[self.index]
self.vel_y +=1
if self.vel_y >25:
self.vel_y =25
dy +=self.vel_y
self.in_air =True
for tile in world.tile_list:
if tile[1].colliderect(self.rect.x+dx,self.rect.y,self.width,self.rect.height):
dx =0
if tile[1].colliderect(self.rect.x,self.rect.y+dy,self.width,self.height):
if self.vel_y <0:
dy =tile[1].bottom -self.rect.top
self.vel_y =0
elif self.vel_y>=0:
dy =tile[1].top -self.rect.bottom
self.vel_y=0
self.in_air =False
if pygame.sprite.spritecollide(self,blob_group,False):
game_over_fx.play()
game_over =-1
if pygame.sprite.spritecollide(self,lava_group,False):
game_over_fx.play()
game_over =-1
if pygame.sprite.spritecollide(self,exit_group,False):
game_over=1
for platform in platform_group:
# collision in the x direction
if platform.rect.colliderect(self.rect.x + dx, self.rect.y, self.width, self.height):
dx = 0
# collision in the y direction
if platform.rect.colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
# check if below platform
if abs((self.rect.top + dy) - platform.rect.bottom) < col_thresh:
self.vel_y = 0
dy = platform.rect.bottom - self.rect.top
# check if above platform
elif abs((self.rect.bottom + dy) - platform.rect.top) < col_thresh:
self.rect.bottom = platform.rect.top-1
self.in_air = False
dy = 0
# move sideways with the platform
if platform.move_x != 0:
self.rect.x += platform.move_direction
self.rect.x +=dx
self.rect.y +=dy
if self.rect.bottom >screen_height:
self.rect.bottom =screen_height
dy =0
elif game_over==-1:
self.image =self.dead_image
draw_text("Game Over",font,blue,(screen_width//2)-200,screen_height//2)
if self.rect.y >200:
self.rect.y-=5
screen.blit(self.image,self.rect)
return game_over
class Enemy(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image =pygame.image.load("blob.png")
self.rect =self.image.get_rect()
self.rect.x =x
self.rect.y =y
self.move_direction =1
self.move_counter =0
def update(self):
self.rect.x +=self.move_direction
self.move_counter+=1
if abs(self.move_counter)>50:
self.move_direction *=-1
self.move_counter *=-1
pygame.draw.rect(screen,(255, 255, 255),self.rect)
class Lava(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
lava_image =pygame.image.load("lava.png")
self.image =pygame.transform.scale(lava_image,(tile_size,tile_size//2))
self.rect =self.image.get_rect()
self.rect.x =x
self.rect.y =y
class Coin(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
coin_image =pygame.image.load("coin.png")
self.image =pygame.transform.scale(coin_image,(tile_size//2,tile_size//2))
self.rect =self.image.get_rect()
self.rect.center=(x,y)
platform_group = pygame.sprite.Group()
#world =World(world_data)
player =Player(100,screen_height-120)
restart_button = Button(screen_width//2, screen_height //2, restart_img)
start_button = Button(screen_width//2, screen_height//2-100, start_image)
exit_button = Button(screen_width//2, screen_height//2 + 200, exit_image)
def draw_grid():
for line in range(0,tile_size+1):
pygame.draw.line(screen,(255,255,255),(0,line*tile_size),(screen_width,line*tile_size))
pygame.draw.line(screen, (255, 255, 255), (line * tile_size,0), (line * tile_size,screen_height))
#load in level data and create world
if path.exists(f'level{level}_data'):
pickle_in = open(f'level{level}_data', 'rb')
world_data = pickle.load(pickle_in)
world = World(world_data)
run =True
while run :
clock.tick(fps)
screen.blit(sky_img,(0,0))
screen.blit(sun_img, (100, 100))
if main_menu==True:
if exit_button.draw():
run =False
if start_button.draw()==True:
main_menu=False
else:
#draw_grid()
world.draw()
if game_over == 0:
blob_group.update()
platform_group.update()
if pygame.sprite.spritecollide(player,coin_group,True):
coin_fx.play()
score += 1
draw_text('X'+str(score),font_score,white,tile_size-10,10)
blob_group.draw(screen)
platform_group.draw(screen)
lava_group.draw(screen)
exit_group.draw(screen)
coin_group.draw(screen)
game_over = player.update(game_over)
if game_over==-1:
if restart_button.draw():
world_data =[]
world =reset_level(level)
game_over =0
score=0
if game_over==1:
level+=1
if level<=max_levels:
world_data =[]
world =reset_level(level)
game_over=0
else:
draw_text("you won",font,blue,(screen_width // 2) - 140, screen_height // 2)
if restart_button.draw():
level =1
world_data =[]
world =reset_level(level)
game_over=0
score=0
for event in pygame.event.get():
if event.type ==pygame.QUIT:
run =False
pygame.display.update()
pygame.quit()
</code></pre>
<p>game works as fine,</p>
<pre><code>but have several issues, one issue is this line :
if platform.move_x != 0:
self.rect.x += platform.move_direction
</code></pre>
<p>it colors as yellow color and says :
<a href="https://i.stack.imgur.com/zdrJM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zdrJM.png" alt="enter image description here" /></a></p>
<p>in shortly it says that <code>Unresolved attribute reference 'move_x' for class 'Sprite'</code> , the same is for platform.move_direction, but in Platform class we have both parameters and both are added here :</p>
<pre><code>if tile == 4:
platform = Platform(col_count * tile_size, row_count * tile_size, 1, 0)
platform_group.add(platform)
if tile == 5:
platform = Platform(col_count * tile_size, row_count * tile_size, 0, 1)
platform_group.add(platform)
</code></pre>
<p>also there is second issue :in game player can't stand on moving platform, i mean this picture :
<a href="https://i.stack.imgur.com/Cmqts.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Cmqts.png" alt="enter image description here" /></a></p>
<p>if player is on platform, it falls down, how can i fix this issue? thanks in advance</p>
| 3 | 8,171 |
xdmp:spawn-function() Alternative
|
<p>we have around "20 million" documents in the database and we have created badges of "10000" and use
<strong>xdmp:spawn-function()</strong> to query over these 20 million documents and perform delete operations according to some conditions . But running it through query console, query is getting timeout .. Any alternate option we can look for so that the query doesn't get timed-out</p>
<pre><code>xquery version "1.0-ml";
declare variable $versionToMaintain := 10;
declare variable $batchSize := 10000;
declare function local:delete($values) {
for $value in $values
let $versionToDelete := $value[3] - $versionToMaintain
return
if ($versionToDelete > 0) then
let $query := cts:and-query((
cts:collection-query('collection name 2'),
cts:element-range-query(xs:QName('version'), '<=', xs:int($versionToDelete)),
cts:element-value-query(xs:QName('id'),$value[2]),
cts:element-range-query(xs:QName('c:created-on'), '<=', xs:dateTime(xdmp:parseDateTime('[Y0001]-[M01]-[D01]')
))
return (cts:uris((), (), $query) ! xdmp:document-delete(.))
else ()
};
let $totalDocs :=
xdmp:estimate(
cts:search(
collection("collection name 1"),
cts:not-query(cts:element-value-query(xs:QName('version'), "1")),
"unfiltered"
)
)
let $totalBatches := fn:ceiling($totalDocs div $batchSize)
for $x in (1 to $totalBatches)
let $values :=
cts:value-tuples(
(
cts:uri-reference(),
cts:element-reference(xs:QName('id')),
cts:element-reference(xs:QName('version'))
),
("skip=" || ($x - 1) * $batchSize, "truncate=" || $batchSize),
cts:and-query((
cts:collection-query("collection name 1"),
cts:not-query(cts:element-value-query(xs:QName('version'), "1"))
))
)
return
xdmp:spawn-function(function(){
local:delete($values)
})
</code></pre>
| 3 | 1,035 |
Toggling State while using react router
|
<p>By default, I want to show the temperature of the current gps location. But if the user wishes to see the temperature of any other specific country he can do so by providing the country name.</p>
<p>I have used HomeLocation as the toggle, such that whenever '/' is rendered the HomeLocation is set to <code>true</code>, an axios request is made to the api using the Geocoordinates, and if the HomeLocation is set to <code>false</code>, an axios request is made using the country name.</p>
<p>I am not sure if this is the correct way to do it any help would be appreciated.</p>
<pre><code>import React from "react";
import "./App.css";
import Dashboard from "./components/Dashboard/Dashboard";
import { Route, Switch } from "react-router";
import SearchBar from "./components/Dashboard/Searchbar";
import NavBar from "./components/Dashboard/Navlink";
import Weekly from "./components/Weekly/WeeklyDashboard";
function getlocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation not supported");
}
}
function showPosition(position) {
console.log(position.coords.latitude);
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
Location: "",
HomeLocation: true,
ResponseDetails: {
City: "",
Country: "",
Geolocation: "",
},
};
}
componentWillMount() {
if (this.state.HomeLocation === true) {
console.log("Make request to open weather api using gps cordinates");
} else {
console.log(
"Make request to open api using the country name provided by the user"
);
}
}
render() {
return (
<div className="Main">
<div className="SearchGroup">
<div>
<SearchBar />
</div>
<div>
<NavBar />
</div>
</div>
<Switch>
<Route path="/" component={() => <Dashboard WeatherDetails={this.state.ResponseDetails} />} exact />
<Route path="/:coutryname" component={() => <Dashboard WeatherDetails={this.state.ResponseDetails}/>} />/
</Switch>
</div>
);
}
}
export default App;
</code></pre>
| 3 | 1,025 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.