title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
I can't save data to a Mongodb database MEAN Stack application
|
<p>so when I created a collection for user LOGIN/LOGOUT it worked perfectly fine I was able to get user data in and out of the database using Express app, mongoose and, but when I tried to create another collection it created the collection but doesn't save the data to MongoDB </p>
<p>this is the component to save my data</p>
<pre><code> @Component({
selector: 'app-save-cv',
templateUrl: './save-cv.component.html',
styleUrls: ['./save-cv.component.css']
})
export class SaveCvComponent implements OnInit {
form:FormGroup = new FormGroup({
nom:new FormControl(null, Validators.required),
prenom:new FormControl(null, Validators.required),
adresse:new FormControl(null, Validators.required)
})
constructor(private _router:Router, private _cvService:CvService) { }
save(){
if(!this.form.valid ){
console.log('Invalid Form'); return;
}
console.log(JSON.stringify(this.form.value));
this._cvService.save(JSON.stringify(this.form.value))
.subscribe(
data=> {console.log(data); this._router.navigate(['/register']);},
error=>console.error(error)
)
}
ngOnInit() {
}
}
</code></pre>
<p>This is the Service i used to connect to my JAVA Script server APP.js</p>
<pre><code>import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
@Injectable()
export class CvService {
constructor(private _http:HttpClient) { }
save(body:any){
return this._http.post('http://127.0.0.1:3000/cvs/save',body,{
observe:'body',
withCredentials:true,
headers:new HttpHeaders().append('Content-Type','application/json')
});}}
</code></pre>
<p>this is the route I used </p>
<pre><code>var express = require('express');
var router = express.Router();
var Cv = require('../models/cv');
var passport = require('passport');
router.post('/save', function (req, res, next) {
addToDB(req, res);
});
async function addToDB(req, res) {
var cv = new Cv({
Nom : req.body.Nom,
Prenom: req.body.Prenom,
Adresse:req.body.Adresse
});
try {
doc = await cv.save();
return res.status(201).json(doc);
}
catch (err) {
return res.status(501).json(err);
}
</code></pre>
<p>}
module.exports = router;</p>
<p>this is my schema </p>
<pre><code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
Nom : {type:String, require:true},
Prenom: {type:String, require:true},
Adresse:{type:String, require:true}
});
module.exports = mongoose.model('Cv',schema);
</code></pre>
<p>i expected the data to be saved in the database but insted i only get </p>
<pre><code> {_id: "5cdc472b8115fb260409dffe", __v: 0}
__v: 0
_id: "5cdc472b8115fb260409dffe"
__proto__: Object}
</code></pre>
| 3 | 1,034 |
Conky Issues: previous wallpaper or application background, double text, old conky text overlap
|
<p><a href="https://i.stack.imgur.com/SaWhI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SaWhI.jpg" alt="enter image description here"></a></p>
<p>I am using Ubuntu 18.04, having multiple issues with my Conky setup.</p>
<p><b>First</b>, I use Variety, changing wallpaper application. Now Conky takes the snap of the earliest wallpaper background and uses it till next restart. The same issue with any application also.</p>
<p><b>Second</b>, the dynamic expressions like top processes or data consumption overlap with the previous value i.e. the old value doesn't get cleaned.</p>
<p><b>Third</b>, my Conky texts are leaving black duplicates with a vertical offset, it seems like I'm running two Conky.</p>
<p>Tried purging and reinstalling Conky but no use.</p>
<p>My <b>conky.conf</b></p>
<pre><code>-- vim: ts=4 sw=4 noet ai cindent syntax=lua
--[[
Conky, a system monitor, based on torsmo
Any original torsmo code is licensed under the BSD license
All code written since the fork of torsmo is licensed under the GPL
Please see COPYING for details
Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
Copyright (c) 2005-2012 Brenden Matthews, Philip Kovacs, et. al. (see AUTHORS)
All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]
conky.config = {
alignment = 'top_left',
background = false,
border_width = 0,
cpu_avg_samples = 2,
own_window_transparent = true,
own_window = true,
default_color = '#7f77e6',
color1 = 'yellow',
color2 = '#0cc99d',
color3 = '#cc6452',
color4 = '#ac5fba',
default_outline_color = 'black',
default_shade_color = 'white',
draw_borders = false,
draw_graph_borders = true,
draw_outline = true,
draw_shades = false,
use_xft = true,
font = 'LCDMono:size=8',
gap_x = 5,
gap_y = 30,
minimum_height = 5,
minimum_width = 5,
net_avg_samples = 2,
no_buffers = true,
out_to_console = false,
out_to_stderr = false,
extra_newline = false,
own_window = true,
own_window_class = 'Conky',
own_window_type = 'desktop',
stippled_borders = 0,
update_interval = 1.0,
uppercase = false,
use_spacer = 'none',
show_graph_scale = false,
show_graph_range = false,
}
conky.text = [[
${alignc}${color red}${font LCDMono:bold:size=8}IP: ${exec curl -s www.icanhazip.com}
${alignc}${color red}${font LCDMono:bold:size=8}WIFI IP: ${addr wlp1s0}
${alignc}${color red}${font LCDMono:bold:size=8}ETHN IP: ${addr enp2s0}
${color}${font LCDMono:size=8}Uptime${font}:$color1 $uptime
${color}${font LCDMono:size=8}Frequency (in MHz)${font}:$color1 $freq
${color}${font LCDMono:size=8}Frequency (in GHz)${font}:$color1 $freq_g
${color}${font LCDMono:size=8}RAM Usage${font}:$color1 $mem/$memmax - $memperc% $color2${membar 4}
${color}${font LCDMono:size=8}Swap Usage${font}:$color1 $swap/$swapmax - $swapperc% $color2${swapbar 4}
${color}${font LCDMono:size=8}CPU Usage${font}:$color1 $cpu% $color2${cpubar 4}
${color}${font LCDMono:size=8}Processes${font}:$color1 $processes ${color}${font LCDMono:size=8}Running${font}:$color1 $running_processes
${color2}$hr
${color}${font LCDMono:size=8}File systems:${font}
$color1/${fs_used /}/${fs_size /}$color2 ${fs_bar 6 /}
${color}${font LCDMono:size=8}Networking WIFI:${font}
${color3}Up:$color2 ${upspeed wlp1s0} ${color3} - Down:$color2 ${downspeed wlp1s0}
${color}${font LCDMono:size=8}Networking EHERNET:${font}
${color3}Up:$color2 ${upspeed enp2s0} ${color3} - Down:$color2 ${downspeed enp2s0}
${color}${font LCDMono:size=8}Networking BLUETOOTH:${font}
${color3}Up:$color2 ${upspeed bnep0} ${color3} - Down:$color2 ${downspeed bnep0}
${color}${font LCDMono:size=8}Networking VMNET1:${font}
${color3}Up:$color2 ${upspeed vmnet1} ${color3} - Down:$color2 ${downspeed vmnet1}
${color}${font LCDMono:size=8}Networking VMNET8:${font}
${color3}Up:$color2 ${upspeed vmnet8} ${color3} - Down:$color2 ${downspeed vmnet8}
${color2}$hr
${color}${font LCDMono:size=8}Name${goto 100} PID CPU% MEM%${font}
${color3} ${top name 1}${goto 100} $color2${top pid 1} ${top cpu 1} ${top mem 1}
${color3} ${top name 2}${goto 100} $color2${top pid 2} ${top cpu 2} ${top mem 2}
${color3} ${top name 3}${goto 100} $color2${top pid 3} ${top cpu 3} ${top mem 3}
${color3} ${top name 4}${goto 100} $color2${top pid 4} ${top cpu 4} ${top mem 4}
${color2}$hr
${color}${font LCDMono:size=8}Total Data Consumption${font}
${color4}Down: ${color green}${totaldown wlp1s0} ${goto 100}${color4} Up: ${color green}${totalup wlp1s0}
${color}${font LCDMono:size=8}Today's Data Consumption${font}
${color1}${font LCDMono:size=6}WIFI:${font}
${color4}Down: ${color green}${execi 60 LC_ALL=C vnstat | grep -A 4 wlp1s0 | grep "today" | awk '{print $2 $3}'}${color4} Up: ${color green}${execi 60 LC_ALL=C vnstat | grep -A 4 wlp1s0 | grep "today" | awk '{print $5 $6}'}${color4} Total: ${color green}${execi 60 LC_ALL=C vnstat | grep -A 4 wlp1s0 | grep "today" | awk '{print $8 $9}'}
${color1}${font LCDMono:size=6}ETHN:${font}
${color4}Down: ${color green}${execi 60 LC_ALL=C vnstat | grep -A 4 enp2s0 | grep "today" | awk '{print $2 $3}'}${color4} Up: ${color green}${execi 60 LC_ALL=C vnstat | grep -A 4 enp2s0 | grep "today" | awk '{print $5 $6}'}${color4} Total: ${color green}${execi 60 LC_ALL=C vnstat | grep -A 4 enp2s0 | grep "today" | awk '{print $8 $9}'}
${color2}$hr
${color green}${font LCDMono:size=6}WIFI Down${alignr}WIFI Up${font}
${color2}${downspeedgraph wlp1s0 15, 120 00B706 FF0000 -t}${alignr}${upspeedgraph wlp1s0 15, 120 00AFB7 FF0000 -t}
${color green}${font LCDMono:size=6}ETHER Down${alignr}ETHER Up${font}
${color2}${downspeedgraph enp2s0 15, 120 00B706 FF0000 -t}${alignr}${upspeedgraph enp2s0 15, 120 00AFB7 FF0000 -t}
${color green}${font LCDMono:size=6}CPU1${goto 60}CPU2${goto 120}CPU3${goto 180}CPU4${font}
${color2}${cpugraph cpu1 15, 60 00B706 FF0000 -t}${cpugraph cpu2 15, 60 00AFB7 FF0000 -t}${cpugraph cpu3 15, 60 00AFB7 FF0000 -t}${cpugraph cpu4 15, 60 00AFB7 FF0000 -t}
${alignc}${color red}${font LCDMono:bold:size=14}You are under watch
]]
</code></pre>
| 3 | 2,680 |
UIButtons not sticking to UIView edges
|
<p>Hi and thanks in advance. I'm attempting to bind two UIButtons to a <code>UIViewController</code>'s <code>view</code> like so:</p>
<p>First by declaring them:</p>
<pre><code>fileprivate var deleteButton: UIButton = UIButton(type: .system)
fileprivate var addButton: UIButton = UIButton(type: .system)
</code></pre>
<p>Next in setting them up:</p>
<pre><code>private func setupButtons() {
deleteButton.setTitle("Delete", for: .normal)
addButton.setTitle("Add", for: .normal)
deleteButton.sizeToFit()
addButton.sizeToFit()
deleteButton.alpha = 1
addButton.alpha = 1
view.addSubview(deleteButton)
view.addSubview(addButton)
view.addConstraint(NSLayoutConstraint(item: deleteButton,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leading,
multiplier: 1.0,
constant: 0))
view.addConstraint(NSLayoutConstraint(item: deleteButton,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1.0,
constant: 0))
view.addConstraint(NSLayoutConstraint(item: addButton,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailing,
multiplier: 1.0,
constant: 0))
view.addConstraint(NSLayoutConstraint(item: addButton,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1.0,
constant: 0))
}
</code></pre>
<p>But running the simulator sticks the two UIButtons in the top left, the default CGRect frames assigned to them both.</p>
<p>Might you know what i'm doing wrong? I feel like i'm close but perhaps it has something to do with re-drawing the view?</p>
<p><a href="https://i.stack.imgur.com/7Zlwh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Zlwh.png" alt="Halp!"></a></p>
| 3 | 1,614 |
How to determine the optimal configuration for batch inputs in tensorflow?
|
<p>Please first see the following code snippets: </p>
<pre><code>def inputs(filenames, batch_size, num_epochs, shuffle=True):
with tf.name_scope('input'):
filename_queue = tf.train.string_input_producer(filenames,
shuffle=shuffle,
capacity=32*batch_size,
num_epochs=num_epochs)
if shuffle:
image, label = read_and_decode_with_random_processing(filename_queue)
images, sparse_labels = tf.train.shuffle_batch([image, label],
batch_size=batch_size,
num_threads=32,
capacity= 16 * batch_size,
min_after_dequeue= 8 * batch_size)
else:
image, label = read_and_decode(filename_queue)
images, sparse_labels = tf.train.batch([image, label],
batch_size=batch_size,
num_threads=32,
capacity=8 * batch_size,
allow_smaller_final_batch=True)
return images, sparse_labels
</code></pre>
<p>there are three <code>capacity</code> variables and two <code>num_threads</code> variables. In my practice, I found these guys are hard to determine to let the GPUs be busy-working. It seems the GPU works too faster than these guys to load the data. How do you determine these numbers in practice? In my opinion, the larger these numbers are, the better it should be (because the queue is always full of data, the GPUs don't need to wait). But if I set these numbers too big, it is slow for the prefetch. Maybe I missed something. </p>
| 3 | 1,024 |
Android MapActivity leak in my Activity's Context related to mNetworkHandler
|
<p>I'm having difficulties tracking down the cause of a leak from my use of MapActivity. I have been using the Eclipse Memory Analysis tool for the past few months to track down various memory leaks within our application, but I can't seem to find a how-to that explains the usage of MapActivity and how to clean up the resources properly.</p>
<p>From MAT, the memory leak seems to be coming from com.google.android.maps.MapActivity's mNetworkHandler keeping My Activity's context alive, and vice versa. On this particular screen, the leak surfaces with each new latitude/longitude that is fed into the MapActivity. If I continually go to this screen with the same coordinates, the leak does not grow.</p>
<p>Below you'll find the (condensed) code that I'm working with. </p>
<pre><code>public class MyMapActivity extends MapActivity
{
MapView mMapView;
List<Overlay> mMapOverlays;
public void onCreate(Bundle savedInstanceState) {
mMapView = (MapView) findViewById(R.id.mapview);
mMapView = new MapView(this, mapApiKey);
mMapView.setClickable(true);
setContentView(mMapView);
mMapView.setBuiltInZoomControls(true);
mMapOverlays = mMapView.getOverlays();
mMapView.postDelayed(Timer_Tick, 20000);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
if (!mResponseProcessed) {
UIHelper.showErrorDialogOnGuiThread(mCurrentActivity, "Error!");
}
}
};
private void showMapObject(String message) {
final MapController mc = mMapView.getController();
mc.animateTo(point);
mc.setZoom(10);
}
protected void onDestroy() {
super.onDestroy();
mMapView.removeCallbacks(Timer_Tick);
Field fConverterInView = MapView.class.getDeclaredField("mConverter");
fConverterInView.setAccessible(true);
fConverterInView.set(mMapView, null);
Field fControllerInView = MapView.class.getDeclaredField("mController");
fControllerInView.setAccessible(true);
fControllerInView.set(mMapView, null);
Field fZoomHelperInView = MapView.class.getDeclaredField("mZoomHelper");
fZoomHelperInView.setAccessible(true);
fZoomHelperInView.set(mMapView, null);
Field fMapInView = MapView.class.getDeclaredField("mMap");
AccessibleObject.setAccessible(new AccessibleObject[] { fMapInView }, true);
fMapInView.set(mMapView, null);
Field mConfigField = MapActivity.class.getDeclaredField("mConfig");
mConfigField.setAccessible(true);
Object mConfig = mConfigField.get(this);
if (null != mConfig) {
Field mConfigContextField = mConfig.getClass().getDeclaredField("context");
mConfigContextField.setAccessible(true);
mConfigContextField.set(mConfig, null);
mConfigField.set(this, null);
}
}
}
</code></pre>
<p>edit::
I believe the mNetworkHandler and my Activity's context are keeping each other alive. From MAT, this is the memory trace to the leak to my context:</p>
<pre><code>------------------------------------------------------------------------------------------------------------------------
class android_maps_conflict_avoidance.com.google.googlenav.StartupHelper @ 0x43a4aef0 System Class
'- startupCallbacksForBgThread java.util.Vector @ 0x43a4b028
'- elementData java.lang.Object[10] @ 0x43854810
|- [2] android_maps_conflict_avoidance.com.google.googlenav.map.MapService$1 @ 0x434e8d80
| '- this$0 android_maps_conflict_avoidance.com.google.googlenav.map.MapService @ 0x43abc930
| '- flashService android_maps_conflict_avoidance.com.google.googlenav.map.MapFlashService @ 0x43abcb00
| '- store android_maps_conflict_avoidance.com.google.common.io.android.AndroidPersistentStore @ 0x4356baf8
| '- context com.my.package.MyMapActivity @ 0x436da020
------------------------------------------------------------------------------------------------------------------------
</code></pre>
<p>Here is the memory leak from the MapActivity object:</p>
<pre><code>------------------------------------------------------------------------------------------------------------------------
class android_maps_conflict_avoidance.com.google.googlenav.StartupHelper @ 0x43a4aef0 System Class
'- startupCallbacksForBgThread java.util.Vector @ 0x43a4b028
'- elementData java.lang.Object[10] @ 0x43854810
|- [3] android_maps_conflict_avoidance.com.google.googlenav.map.MapService$1 @ 0x43837938
| '- this$0 android_maps_conflict_avoidance.com.google.googlenav.map.MapService @ 0x43201cf8
| '- flashService android_maps_conflict_avoidance.com.google.googlenav.map.MapFlashService @ 0x43238470
| '- store android_maps_conflict_avoidance.com.google.common.io.android.AndroidPersistentStore @ 0x435e6730
| '- context com.my.package.MyMapActivity @ 0x43822250
| '- mNetworkHandler com.google.android.maps.MapActivity$1 @ 0x43822488
------------------------------------------------------------------------------------------------------------------------
</code></pre>
<p>AndroidPersistentStore is holding a reference to my Activity's context, and my context is holding a reference to the mNetworkHandler within MapActivity. I don't see how to release these 2 objects.</p>
| 3 | 2,436 |
Error 500 jsf.js link in spring webflow + myfaces app
|
<p>I develop spring and myfaces app and it produces nonaccessible link to jsf.js.
Generated page contains link which points to dispatcher servlet:</p>
<pre><code><script type="text/javascript" src="/myapp/app/javax.faces.resource/jsf.js?ln=javax.faces&amp;stage=Development"></script`>
</code></pre>
<p>This URL gives error 500:
/WEB-INF/application/javax.faces.resource/jsf.xhtml Not Found in ExternalContext as a Resource</p>
<pre><code>viewId=/WEB-INF/application/javax.faces.resource/jsf.xhtml
</code></pre>
<p>but I found out that working one is <code>/myapp/faces/javax.faces.resource/jsf.js</code></p>
<p>So, it looks like it produces link to dispatcher servlet, not to faces one, in my web.xml I made following declarations:</p>
<pre class="lang-xml prettyprint-override"><code><servlet>
<servlet-name>Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value><![CDATA[
/WEB-INF/config/webmvc-config.xml
/WEB-INF/config/webflow-config.xml
classpath:view-config.xml ]]>
</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Dispatcher Servlet</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Resources Servlet</servlet-name>
<servlet-class>org.springframework.js.resource.ResourceServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Resources Servlet</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
</code></pre>
<p>I am using spring 3.2.6 and myfaces 2.2.4 now, but I tried both to upgrade spring and downgrade myfaces with the same result.</p>
<p>Besides ajax functionality application is working - view is rendered and links to other flow pages work as well.</p>
<p>What I am missing? Which configuration options should I check?</p>
<p>Greetings</p>
| 3 | 1,207 |
while loop to compare files with each other
|
<p>I achived result from for loop as below. Only thing to avoid is to compare same files.</p>
<pre><code> $ for (( i = 0; i <= 9; i++ )) ### Outer for loop ###
> do
>
> for (( j = 0 ; j <= 9; j++ )) ### Inner for loop ###
> do
> echo "awk -f cmp.awk SPM_CC"$j"_Log" SPM_CC"$i"_Log" > SPM_CC"$j"_DWN"""
> done
>
>
> done
awk -f cmp.awk SPM_CC0_Log SPM_CC0_Log > SPM_CC0_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC0_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC0_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC0_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC0_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC0_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC0_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC0_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC0_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC0_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC0_Log SPM_CC1_Log > SPM_CC0_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC1_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC1_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC1_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC1_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC1_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC1_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC1_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC1_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC1_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC0_Log SPM_CC2_Log > SPM_CC0_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC2_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC2_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC2_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC2_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC2_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC2_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC2_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC2_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC2_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC0_Log SPM_CC3_Log > SPM_CC0_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC3_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC3_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC3_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC3_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC3_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC3_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC3_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC3_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC3_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC0_Log SPM_CC4_Log > SPM_CC0_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC4_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC4_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC4_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC4_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC4_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC4_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC4_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC4_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC4_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC0_Log SPM_CC5_Log > SPM_CC0_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC5_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC5_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC5_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC5_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC5_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC5_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC5_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC5_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC5_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC0_Log SPM_CC6_Log > SPM_CC0_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC6_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC6_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC6_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC6_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC6_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC6_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC6_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC6_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC6_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC0_Log SPM_CC7_Log > SPM_CC0_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC7_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC7_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC7_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC7_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC7_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC7_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC7_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC7_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC7_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC0_Log SPM_CC8_Log > SPM_CC0_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC8_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC8_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC8_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC8_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC8_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC8_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC8_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC8_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC8_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC0_Log SPM_CC9_Log > SPM_CC0_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC9_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC9_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC9_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC9_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC9_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC9_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC9_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC9_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC9_Log > SPM_CC9_DWN
</code></pre>
<p>I need to fetch various linux command out of loop where Files need to compare with each others. In order to get same need to contruct double while loop.</p>
<p>For example: SPM_CC1_Log with SPM_CC0_Log to SPM_CC9_Log and vice versa.</p>
<p>Here is my while loop</p>
<pre><code>
n=9
i=0
while [ $i -le $n ]
do
j=1
while [ $j -le $n ]
do
echo "awk -f cmp.awk SPM_CC"$j"_Log" SPM_CC"$i"_Log" > SPM_CC"$j"_DWN"""
i=$((i+1))
j=$((j+1))
done
done
awk -f cmp.awk SPM_CC1_Log SPM_CC0_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC1_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC3_Log SPM_CC2_Log > SPM_CC3_DWN
awk -f cmp.awk SPM_CC4_Log SPM_CC3_Log > SPM_CC4_DWN
awk -f cmp.awk SPM_CC5_Log SPM_CC4_Log > SPM_CC5_DWN
awk -f cmp.awk SPM_CC6_Log SPM_CC5_Log > SPM_CC6_DWN
awk -f cmp.awk SPM_CC7_Log SPM_CC6_Log > SPM_CC7_DWN
awk -f cmp.awk SPM_CC8_Log SPM_CC7_Log > SPM_CC8_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC8_Log > SPM_CC9_DWN
</code></pre>
<p>Whereas I need below output from while loop to compare each files with each other.</p>
<pre><code>
awk -f cmp.awk SPM_CC1_Log SPM_CC0_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC1_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC2_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC3_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC4_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC5_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC6_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC7_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC8_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC1_Log SPM_CC9_Log > SPM_CC1_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC0_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC1_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC2_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC3_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC4_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC5_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC6_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC7_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC8_Log > SPM_CC2_DWN
awk -f cmp.awk SPM_CC2_Log SPM_CC9_Log > SPM_CC2_DWN
----
----
----
----
awk -f cmp.awk SPM_CC9_Log SPM_CC1_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC2_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC3_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC4_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC5_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC6_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC7_Log > SPM_CC9_DWN
awk -f cmp.awk SPM_CC9_Log SPM_CC8_Log > SPM_CC9_DWN
</code></pre>
| 3 | 5,072 |
How To Mock redux-promise-listener Middleware And final-form
|
<p>I setup <code>react-redux-promise-listener</code> <a href="https://github.com/erikras/react-redux-promise-listener" rel="nofollow noreferrer">(repo)</a> for <code>react-final-form</code> via <a href="https://medium.com/@erikras/getting-a-promise-from-redux-actions-d92787894368" rel="nofollow noreferrer">author instructions</a>. Now, I'm having trouble mocking it for testing. </p>
<p>I'm getting error: <code>The redux-promise-listener middleware is not installed</code></p>
<p>I've tried applying middleware within the test provider: </p>
<pre><code>// app/frontend/__mocks__/TestReduxProvider.js
import React from 'react';
import { createStore, applyMiddleware } from 'redux';
import { Provider as ReduxProvider } from 'react-redux';
import { compose, setDisplayName, defaultProps } from 'recompose';
import createReduxPromiseListener from 'redux-promise-listener';
import rootReducer from '../store/rootReducer';
const displayName = 'TestReduxProvider';
const enhance = compose(
setDisplayName(displayName),
defaultProps({ state: {} }),
);
const reduxPromiseListener = createReduxPromiseListener();
function TestReduxProvider(props) {
const { state, children } = props;
const store = createStore(
rootReducer,
state,
applyMiddleware(reduxPromiseListener.middleware),
);
return <ReduxProvider store={store}>{children}</ReduxProvider>;
}
export const promiseListener = reduxPromiseListener;
export default enhance(TestReduxProvider);
</code></pre>
<pre><code>// sample test
import React from 'react';
import TestReduxProvider from '~/__mocks__/TestReduxProvider';
import { render } from 'enzyme';
import Form from '../Form';
it('should not break if no params', () => {
const wrapper = render(
<TestReduxProvider>
<Form />
</TestReduxProvider>
);
expect(wrapper).toMatchSnapshot();
});
</code></pre>
<pre><code>// form component relevant
import { connect } from 'react-redux';
import { Form as FormHandler } from 'react-final-form';
import MakeAsyncFunction from 'react-redux-promise-listener';
import { promiseListener } from '~/store/createStore';
import {
STATUS_SUCCESS,
STATUS_FAILURE,
} from '~/store/modules/async/constants';
const Form = props => {
const targetFormErrors = formErrors[targetAction] || '';
return (
<StyledForm >
<MakeAsyncFunction
listener={promiseListener}
start={targetAction}
resolve={`${targetAction}/${STATUS_SUCCESS}`}
reject={`${targetAction}/${STATUS_FAILURE}`}
setPayload={setPayloadHandler}
>
{asyncFunc => (
<FormHandler
onSubmit={asyncFunc}
validate={isValid}
initialValues={formattedInitialValues}
render={({ handleSubmit, pristine, errors, form }) => {
if (navigationState !== 'form') {
form.reset();
}
return (
<form
onSubmit={event => {
setSubmitAttempted(true);
handleSubmit(event)
.then(() => submitSuccessHandler(form))
.catch(() => {
});
}}
>
{inputsArray.map(formObject => {
return (
<div key={formObject.property}>
<label>
{formObject.label}
{formObject.isRequired !== false && !isDisabled && (
<span className="required"> *</span>
)}
<InputContainer>
<Input
formObject={formObject}
isDisabled={isDisabled}
/>
</InputContainer>
</label>
</div>
);
})}
</form>
);
}}
/>
)}
</MakeAsyncFunction>
</StyledForm>
);
};
export default enhance(Form);
</code></pre>
<p>I was expecting the snapshot to render. However, I got an error instead:</p>
<pre><code>
The redux-promise-listener middleware is not installed
103 | },
104 | ];
> 105 | const wrapper = render(
| ^
106 | <TestReduxProvider>
107 | <Form inputsArray={INPUTS_ARRAY} />
108 | </TestReduxProvider>
at Object.createAsyncFunction (node_modules/redux-promise-listener/dist/redux-promise-listener.cjs.js:60:13)
at new MakeAsyncFunction (node_modules/react-redux-promise-listener/dist/react-redux-promise-listener.cjs.js:82:31)
at processChild (node_modules/react-dom/cjs/react-dom-server.node.development.js:2846:14)
at resolve (node_modules/react-dom/cjs/react-dom-server.node.development.js:2812:5)
at ReactDOMServerRenderer.render (node_modules/react-dom/cjs/react-dom-server.node.development.js:3202:22)
at ReactDOMServerRenderer.read (node_modules/react-dom/cjs/react-dom-server.node.development.js:3161:29)
at Object.renderToStaticMarkup (node_modules/react-dom/cjs/react-dom-server.node.development.js:3661:27)
at Object.renderToStaticMarkup [as render] (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:742:31)
at render (node_modules/enzyme/src/render.js:21:25)
at Object.<anonymous> (app/frontend/components/views/dashboard/views/accounts/components/__tests__/Form.test.js:105:19)
</code></pre>
| 3 | 2,694 |
How to pass a PHP id to create two bootstrap button diffrent id's and use its for jquery functin?
|
<pre><code><?php
include_once('config.php');
$sql="SELECT * FROM events";
$result = mysqli_query($con,$sql);
if(!$result)
{
echo "no record found";
}
else
{
while ($row =mysqli_fetch_assoc($result))
{
$e_id=$row['e_id'];
?>
<?php
$_SESSION['r']=$e_id."rr";
$_SESSION['l']=$e_id."ll";
?>
<p>
<a class="btn btn-default" id="<?php echo $_SESSION['r']; ?>" role="button" data-toggle="collapse" href="#<?php echo $e_id; ?>" aria-expanded="false" aria-controls="<?php echo $e_id; ?>">View More &raquo;</a>
<a class="btn btn-default" id="<?php echo $_SESSION['l']; ?>" role="button" data-toggle="collapse" href="#<?php echo $e_id; ?>" aria-expanded="false" aria-controls="<?php echo $e_id; ?>">View Less &laquo;</a></br>
</p>
<script>
var l = "<?php echo $_SESSION['l'];?>";
var r = "<?php echo $_SESSION['r'];?>";
alert(r);
$(document).ready(function(){
$("#"+r).show();
$("#"+l).hide();
$("#"+l).click(function(){
$("#"+l).hide();
$("#"+r).show();
});
$("#"+r).click(function(){
$("#"+r).hide();
$("#"+l).show();
});
});
</script>
<?php
}//while
}//else
?>
</code></pre>
<p>I fetch data $e_id from database then use it to create two buttons with added char to differ rr and ll as their id's then store in session. Now how to use it in jquery to show/hide each one. data-toggle on button is different div works fine. If i alert(r) gives 1rr 2rr 3rr, and alert(l) 1ll 2ll 3ll. I have 1,2,3 as id in database how can i use this button id's in script. session_start() was on top of page. The problem is hide/show not working guess I'm doing wrong. How can I call that id's properly?</p>
| 3 | 1,452 |
C# gridview column order reset
|
<p>I am trying to dynamically reorder gridview columns based on the needs of a user for a web application. </p>
<p>Say for example the default table starts with the columns A B C D ... W X Y Z.</p>
<p>The user brings up another table but it must have the order C D E F... Y Z A B.</p>
<p>The current implementation I have is the following:</p>
<pre><code> <asp:GridView ID="lettertable" ClientIDMode="Static" runat="server" NullDisplayText="" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="A" ReadOnly="false" ItemStyle-CssClass="tlet ssA" />
<asp:BoundField DataField="B" ReadOnly="false" ItemStyle-CssClass="tlet ssB" />
<asp:BoundField DataField="C" ReadOnly="false" ItemStyle-CssClass="tlet ssC" />
<asp:BoundField DataField="D" ReadOnly="false" ItemStyle-CssClass="tlet ssD" />
<asp:BoundField DataField="E" ReadOnly="false" ItemStyle-CssClass="tlet ssE" />
...etc
</Columns>
</asp:GridView>
</code></pre>
<p>The codebehind involves a rather extensive set of conditionals (to account for startup vs nonstartup, vs same set of records vs across different) that look like the following:</p>
<pre><code> if (letchg == 0)
{
for (int i = 1; i < rep; i++)
{
var columnMove = grid.Columns[1];
grid.Columns.RemoveAt(1);
grid.Columns.Insert((26), columnMove);
}
}
if (letchg == 2)
{
for (int i = 1; i < rep; i++)
{
var columnMove = grid.Columns[1];
grid.Columns.RemoveAt(1);
grid.Columns.Insert((26), columnMove);
}
}
if (letchg == -2)
{
for (int i = 1; i < rep; i++)
{
var columnMove = grid.Columns[1];
grid.Columns.RemoveAt(1);
grid.Columns.Insert((26), columnMove);
}
}
}
</code></pre>
<p>There are different conditions for startup vs switching between tables, because once I reorder the columns from ABCD...WXYZ to CDEF...YZAB, it stays that way. So if I wanted to go to DEFG...ZABC, I move only one column, since it is relative. The BIG PROBLEM is that if the user hits the refresh button (creating a postback), it will resend the last operation, screwing up the whole order. </p>
<p>Is it possible to just reset the column order of the table every time to ABCD...WXYZ before conducting the reordering? That way it is not a relative reordering? Or is there a better way to do this?</p>
| 3 | 1,308 |
CycleJS makeHTTPDriver _add is not a function
|
<p>Just getting started with CycleJs and I've hit a wall with this error. </p>
<p>Basically, I'm running the <a href="https://github.com/cyclejs/cyclejs/tree/master/examples/isomorphic" rel="nofollow noreferrer">isomorphic example</a>
and adding on HTTP Driver so I can send requests</p>
<p>server.js</p>
<pre><code>function wrapAppResultWithBoilerplate(appFn, context$, bundle$) {
return function wrappedAppFn(sources) {
const vdom$ = appFn(sources).DOM;
const wrappedVDOM$ = xs
.combine(vdom$, context$, bundle$.take(1))
.map(wrapVTreeWithHTMLBoilerplate)
.last();
return Object.assign({}, sources, { DOM: wrappedVDOM$ });
};
}
...
const context$ = xs.of({ route: req.url });
const wrappedAppFn = wrapAppResultWithBoilerplate(
app,
context$,
clientBundle$
);
run(wrappedAppFn, {
DOM: makeHTMLDriver(html => res.send(prependHTML5Doctype(html))),
context: () => context$,
PreventDefault: () => {},
HTTP: makeHTTPDriver()
});
...
</code></pre>
<p>Stacktrace</p>
<pre><code>TypeError: (intermediate value)(intermediate value)._add is not a function
at MapFlatten._n (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:954:35)
at Stream._n (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:1193:22)
at CombineListener._n (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:345:30)
at MemoryStream.Stream._n (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:1193:22)
at MemoryStream._n (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:2110:13)
at StartWith._start (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:1112:14)
at MemoryStream._add (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:2128:23)
at Combine._start (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:396:14)
at Stream._add (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:1250:23)
at MapFlatten._start (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:928:20)
at Stream._add (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:1250:23)
at Combine._start (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:396:14)
at Stream._add (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:1250:23)
at MapOp._start (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:983:14)
at Stream._add (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:1250:23)
at Last._start (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:851:14)
at Stream._add (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:1250:23)
at Stream.addListener (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:1310:10)
at Stream.subscribe (/Users/jethrolarson/github/isomorphic/node_modules/xstream/src/index.ts:1330:10)
at /Users/jethrolarson/github/isomorphic/node_modules/@cycle/run/src/index.ts:143:54
at Array.map (native)
at replicateMany (/Users/jethrolarson/github/isomorphic/node_modules/@cycle/run/src/index.ts:143:6)
at run (/Users/jethrolarson/github/isomorphic/node_modules/@cycle/run/src/index.ts:230:32)
at run (/Users/jethrolarson/github/isomorphic/node_modules/@cycle/run/src/index.ts:272:10)
at /Users/jethrolarson/github/isomorphic/server.js:105:5
at Layer.handle [as handle_request] (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:317:13)
at /Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:335:12)
at next (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:275:10)
at expressInit (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/middleware/init.js:40:5)
at Layer.handle [as handle_request] (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:317:13)
at /Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:335:12)
at next (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:275:10)
at query (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/middleware/query.js:44:5)
at Layer.handle [as handle_request] (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:317:13)
at /Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:335:12)
at next (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/router/index.js:174:3)
at EventEmitter.handle (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/application.js:174:10)
at Server.app (/Users/jethrolarson/github/isomorphic/node_modules/express/lib/express.js:38:9)
at emitTwo (events.js:106:13)
at Server.emit (events.js:191:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:543:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:105:23)
</code></pre>
| 3 | 2,106 |
iOS AFJSONRequestOperation returns empty results
|
<p>I am trying to retrieve data using from a JSON request using AFJSONRequestOperation.
On success I am able to successfully retrieve the data but unable to complete the request and forward the data further for processing.</p>
<p>Following is my code</p>
<pre><code>-(void) retrieveBrandList:(void (^)(NSArray *brandList))success failure:(void (^)(NSError *error))failure
{
//__block NSArray *brandList =[[NSArray alloc] init];
NSString *BrandListURL= http://127.0.0.1:8888/know/rest/brand
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSLog(@"Brand List URL = %@", BrandListURL);
AFJSONRequestOperation *operation =[AFJSONRequestOperation
JSONRequestOperationWithRequest: request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject)
{
NSLog(@"%@", responseObject);
brandList = [self successBandList:responseObject]; // parsing the JSON response in separate method (success block code)
if (success)
success(brandList);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject)
{
message:[NSString stringWithFormat:@"%@",error];
if (failure)
failure(error);
}];
[operation start];
[operation waitUntilFinished];
}
</code></pre>
<p>Following is the data manager to retrieve data.</p>
<pre><code>- (NSArray *)getBrandList
{
@try
{
[brand retrieveBrandList:^(NSArray *brandList)
{
brands = brandList;
}
failure:^(NSError *error) {
}];
NSLog(@"Retriving Brand list completed");
return brands;
}
@catch (NSException * e) {
NSLog(@"Exception: %@ , Error while getting the brand list", e);
}
return NULL;
}
</code></pre>
<p>How do i complete the operation and use or store the results for further processing in some other method?</p>
| 3 | 1,220 |
mysql on docker: Can't start server : Bind on unix socket: Invalid argument
|
<p>I have docker compose yaml:</p>
<pre><code>version: "3.8"
services:
mysql:
image: mysql/mysql-server:8.0.27
container_name: javanotifications_mysql
volumes:
- ./persistence/mysql_db:/var/lib/mysql
</code></pre>
<p>and after running</p>
<pre><code>docker compose up
</code></pre>
<p>I got</p>
<pre><code>[Entrypoint] MySQL Docker Image 8.0.27-1.2.6-server
[Entrypoint] Starting MySQL 8.0.27-1.2.6-server
2022-04-22T23:45:52.061082Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.27) starting as process 1
2022-04-22T23:45:52.065609Z 0 [Warning] [MY-010159] [Server] Setting lower_case_table_names=2 because file system for /var/lib/mysql/ is case insensitive
2022-04-22T23:45:52.077805Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2022-04-22T23:45:52.534236Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2022-04-22T23:45:52.803994Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
2022-04-22T23:45:52.804064Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
2022-04-22T23:45:52.808602Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2022-04-22T23:45:52.808689Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2022-04-22T23:45:52.818496Z 0 [ERROR] [MY-010270] [Server] Can't start server : Bind on unix socket: Invalid argument
2022-04-22T23:45:52.818539Z 0 [ERROR] [MY-010258] [Server] Do you already have another mysqld server running on socket: /var/lib/mysql/mysql.sock ?
2022-04-22T23:45:52.818778Z 0 [ERROR] [MY-010119] [Server] Aborting
2022-04-22T23:45:54.322278Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.27) MySQL Community Server - GPL.
</code></pre>
<p>and container dies.</p>
<p>After cleaning "persistence" directory and repeating the process everything is the same</p>
<p>The only thing that comes to my mind is that it has some problems with /var/lib/mysql/mysql.sock, mysql doesn't like to have it (maybe) in mounted directory.</p>
<p>Then question comes, how to tell mysql to create it somewhere else in the container - beyond mounted directory /var/lib/mysql/?</p>
<pre><code>Docker version 20.10.14, build a224086
MacBook Pro 16-inch, 2019, 2.4 GHz 8-Core Intel Core i9
macOS Big Sur version 11.6
</code></pre>
<p>--------- edit -----</p>
<p>So based on suggestion provided below by Sergio Santiago i've ended up with this solution, which works perfectly, eliminating this error:</p>
<pre><code>version: "3.8"
services:
mysql:
image: mysql/mysql-server:8.0.27
container_name: javanotifications_mysql
ports:
- "${MYSQL_PORT}:3306"
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_PASS}
MYSQL_ROOT_HOST: "%"
volumes:
- ./mysql/my.cnf:/etc/my.cnf
- ./mysql_db/${PROJECT_NAME}:/var/data
</code></pre>
<p>where mysql/my.cnf have this content</p>
<pre><code># For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html
[mysqld]
#
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
#
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
#
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
# Remove leading # to revert to previous value for default_authentication_plugin,
# this will increase compatibility with older clients. For background, see:
# https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_default_authentication_plugin
# default-authentication-plugin=mysql_native_password
skip-host-cache
skip-name-resolve
socket=/var/lib/mysql/mysql.sock
secure-file-priv=/var/lib/mysql-files
user=mysql
pid-file=/var/run/mysqld/mysqld.pid
# modified by US VVV
# NOTE: original localization of the my.cnf in the image is /etc/my.cnf
datadir=/var/data
</code></pre>
| 3 | 1,641 |
CakePHP 3.x DB mapping, BelongsToMany vs HasMany+HasOne
|
<p>I have three tables in DB: (1) <em>offers</em>, (2) <em>offer_rows</em>, (3) <em>products</em>.</p>
<p><em>offer_rows</em> will always point to a <em>offer</em>, and possibly (but not always) to a <em>product</em>. <em>offer_rows</em> has also other fields such as price etc.</p>
<p>Same with (My)SQL:</p>
<pre><code>create table offers(
id serial not null auto_increment primary key,
...
);
create table offer_rows(
id serial not null auto_increment primary key,
product_id bigint(20) unsigned references products(id),
offer_id bigint(20) unsigned not null references offers(id),
price decimal(15,2),
...
);
create table products(
id serial not null auto_increment primary key,
...
);
</code></pre>
<p>In terms of CakePHP (3.3.16), <strong>with the optional reference to a product</strong>, what is the correct mapping?</p>
<p>If the <em>offer_rows</em> had a not null restriction to product reference (which it currently does not have), it would seem that a <strong>BelongsToMany</strong> should be used:</p>
<pre><code>(class OffersTable)
@property \Cake\ORM\Association\BelongsToMany $Products
// initialize
$this->belongsToMany('Products', [
'through' => 'OfferRows',
'foreignKey' => 'offer_id',
'joinType' => 'INNER',
'joinTable' => 'offer_rows',
]);
(class OfferRowsTable)
@property \Cake\ORM\Association\BelongsTo $Products
@property \Cake\ORM\Association\BelongsTo $Offers
// initialize
$this->belongsTo('Products', [
'foreignKey' => 'product_id'
]);
$this->belongsTo('Offers', [
'foreignKey' => 'offer_id',
'joinType' => 'INNER'
]);
(class ProductsTable)
@property \Cake\ORM\Association\BelongsToMany $Offers
// initialize
$this->belongsToMany('Offers', [
'through' => 'OfferRows',
'foreignKey' => 'product_id',
'joinType' => 'INNER',
'joinTable' => 'offer_rows',
]);
</code></pre>
<p>However, with the possibility of the null product, should I use HasMany + HasOne instead?</p>
<pre><code>(class OffersTable)
@property \Cake\ORM\Association\HasMany $OfferRows
// initialize
$this->hasMany('OfferRows', [
'foreignKey' => 'offer_id'
]);
(class OfferRowsTable)
@property \Cake\ORM\Association\BelongsTo $Offers
@property \Cake\ORM\Association\HasOne $Products
// initialize
$this->belongsTo('Offers', [
'foreignKey' => 'offer_id',
'joinType' => 'INNER'
]);
$this->hasOne('Products', [
'className' => 'Products',
'propertyName' => 'reference_product_obj',
'foreignKey' => 'reference_product'
]);
(class ProductsTable)
@property \Cake\ORM\Association\BelongsToMany $OfferRows
// initialize
$this->belongsToMany('OfferRows', [
'foreignKey' => 'product_id',
'joinType' => 'INNER',
]);
</code></pre>
<p>Is either one correct, or is there third alternative?</p>
| 3 | 1,175 |
MVVM and DI with nested controls
|
<p>I've been using MVVM for WPF quite a while now but I've always been doing it this way:</p>
<p><strong>ExampleView.xaml.cs</strong> (namespace: Example.Views)</p>
<pre><code>public partial class ExampleView
{
public ExampleView()
{
InitializeComponent();
var viewModel = new ExampleViewModel();
DataContext = viewModel;
}
}
</code></pre>
<p>The <strong>ExampleView.xaml</strong> has no code concerning the <code>ExampleViewModel</code> except for bindings to properties.</p>
<p><strong>ExampleViewModel.cs</strong> (namespace: Example.ViewModels)</p>
<pre><code>public ExampleViewModel()
{
// No important code in here concerning this topic. Code here is only used in this class.
}
</code></pre>
<p>Below is a simplified <strong>MainWindowView.xaml</strong>.</p>
<pre><code><Window ...
xmlns:views="clr-namespace:Example.Views">
<Grid>
<views:ExampleView />
</Grid>
</Window>
</code></pre>
<p>The <strong>MainWindowView.xaml.cs</strong> is similar to the ExampleView.xaml.cs. The <strong>MainWindowViewModel.cs</strong> has no important code concerning this topic.</p>
<p>Lastly, the <strong>App.xaml</strong> contains the <code>StartupUri="Views/MainWindowView.xaml"</code>.</p>
<p>If this is a good pattern or not, I got my application to work. Since the application is not maintainable by me alone anymore, 2-3 people are now working on it creating some problems. One person is doing the majority of the coding (ViewModels basically), one person is doing the GUI (Views) and one person is doing the "framework" coding. <em>(Using "" because this is not really a framework but I can't think of a better word for it.)</em></p>
<p>Now, I'm the guy that is doing the framework coding and I've been reading up on several subjects like dependency injection and the code below is what I came up with using <code>UnityContainer</code> from Windows.</p>
<p><strong>ExampleView.xaml.cs</strong> (namespace: Example.Views)</p>
<pre><code>public partial class ExampleView
{
public ExampleView()
{
InitializeComponent();
}
}
</code></pre>
<p>The <strong>ExampleView.xaml</strong> has no code concerning the <code>ExampleViewModel</code> except for bindings to properties.</p>
<p><strong>ExampleViewModel.cs</strong> (namespace: Example.ViewModels)</p>
<pre><code>public string MyText { get; set; }
public ExampleViewModel(ILocalizer localizer)
{
MyText = localizer.GetString("Title");
}
</code></pre>
<p>Below is a simplified <strong>MainWindowView.xaml</strong>.</p>
<pre><code><Window ...
xmlns:views="clr-namespace:Example.Views">
<Grid>
<views:ExampleView DataContext="{Binding ExampleViewModel}" />
</Grid>
</Window>
</code></pre>
<p>The <strong>MainWindowView.xaml.cs</strong> is similar to the ExampleView.xaml.cs.</p>
<p><strong>MainWindowViewModel.cs</strong></p>
<pre><code>ExampleViewModel ExampleViewModel { get; set; }
private readonly ILocalizer _localizer;
private readonly IExceptionHandler _exHandler;
public MainWindowViewModel(ILocalizer localizer, IExceptionHandler exHandler)
{
_localizer = localizer;
_exHandler = exHandler;
ExampleViewModel = new ExampleViewModel(localizer);
}
</code></pre>
<p>Lastly, the <strong>App.xaml</strong> does not contains the <code>StartupUri="..."</code> anymore. It's now done in <strong>App.xaml.cs</strong>. It's also here where the `UnityContainer is initialized.</p>
<pre><code>protected override void OnStartup(StartupEventArgs e)
{
// Base startup.
base.OnStartup(e);
// Initialize the container.
var container = new UnityContainer();
// Register types and instances with the container.
container.RegisterType<ILocalizer, Localizer>();
container.RegisterType<IExceptionHandler, ExceptionHandler>();
// For some reason I need to initialize this myself. See further in post what the constructor is of the Localizer and ExceptionHandler classes.
container.RegisterInstance<ILocalizer>(new Localizer());
container.RegisterInstance<IExceptionHandler>(new ExceptionHandler());
container.RegisterType<MainWindowViewModel>();
// Initialize the main window.
var mainWindowView = new MainWindowView { DataContext = container.Resolve<MainWindowViewModel>() };
// This is a self made alternative to the default MessageBox. This is a static class with a private constructor like the default MessageBox.
MyMessageBox.Initialize(mainWindowView, container.Resolve<ILocalizer>());
// Show the main window.
mainWindowView.Show();
}
</code></pre>
<p>For some reason I need to initialize the Localizer and ExceptionHandler classes myself. The Localizer and ExceptionHandler constructors are found below. Both have constructors with all arguments that have a default value. Adding constructors without arguments like </p>
<pre><code>public ExceptionHandler() : this(Path.Combine(Directory.GetCurrentDirectory(), "ErrorLogs", DateTime.Now.ToString("dd-MM-yyyy") + ".log")) { }
</code></pre>
<p>doesn't change a thing.</p>
<pre><code>public Localizer(ResourceDictionary appResDic = null, string projectName = null, string languagesDirectoryName = "Languages", string fileBaseName = "Language", string fallbackLanguage = "en")
{
_appResDic = appResDic ?? Application.Current.Resources;
_projectName = !string.IsNullOrEmpty(projectName) ? projectName : Application.Current.ToString().Split('.')[0];
_languagesDirectoryName = languagesDirectoryName.ThrowArgNullExIfNullOrEmpty("languagesFolder", "0X000000066::The languages directory name can't be null or an empty string.");
_fileBaseName = fileBaseName.ThrowArgNullExIfNullOrEmpty("fileBaseName", "0X000000067::The base name of the language files can't be null or an empty string.");
_fallbackLanguage = fallbackLanguage.ThrowArgNullExIfNullOrEmpty("fallbackLanguage", "0X000000068::The fallback language can't be null or an empty string.");
CurrentLanguage = _fallbackLanguage;
}
public ExceptionHandler(string logLocation = null, ILocalizer localizer = null)
{
// Check if the log location is not null or an empty string.
LogLocation = string.IsNullOrEmpty(logLocation) ? Path.Combine(Directory.GetCurrentDirectory(), "ErrorLogs", DateTime.Now.ToString("dd-MM-yyyy") + ".log") : logLocation;
_localizer = localizer;
}
</code></pre>
<p>My big question now is if I'm approaching dependency injection correctly and if having several static classes that I initialize once are bad. Several topics I've read state that static classes are a bad-practice because of bad testability and tightly coupled code, but right now the tradeoffs of dependency injection are bigger than having static classes.</p>
<p>Doing dependency injection correctly would be a first step in having less tightly coupled code though. I like the approach with the static <code>MyMessageBox</code> I can initialize once and that it's globally available in the application. This is mainly for "easy usage" I guess cause I can simply call <code>MyMessageBox.Show(...)</code> instead of injecting this all the way down to the smallest element. I have a similar opinion about the <code>Localizer</code> and <code>ExceptionHandler</code> because these will be used even more.</p>
<p>A last concern I have is the following. Lets say I have a class with several arguments and one of the arguments is the <code>Localizer</code> (because this will be used in nearly any class). Having to add <code>ILocalizer localizer</code> every time </p>
<pre><code>var myClass = new MyClass(..., ILocalizer localizer);
</code></pre>
<p>feels very annoying. This would push me towards a static Localizer I initialize once and having never to care about it anymore. How would this problem be tackled?</p>
| 3 | 2,394 |
why is this OCMock verify failing?
|
<p>Not sure if I'm using OCMocks correctly, or if it's because I'm using the cocoapods version and not the .lib file.</p>
<p>Here's the test(s)</p>
<pre><code>#import "MWViewControllerTests.h"
#import "MWViewController.h"
#import "OCMockObject.h"
#import "MWGoogleTrends.h"
#import "OCMockRecorder.h"
@implementation MWViewControllerTests {
MWViewController *vcSUT;
id googleTrends;
NSArray *trends;
}
- (void)setUp
{
[super setUp];
vcSUT = [[MWViewController alloc] init];
googleTrends = [OCMockObject mockForClass:[MWGoogleTrends class]];
vcSUT.googleTrends = googleTrends;
trends = [[NSArray alloc] initWithObjects:@"trend1", @"trend2", @"trend3", nil];
[[[googleTrends stub] andReturn:trends] getLatestTrends];
}
- (void)tearDown
{
// Tear-down code here.
[super tearDown];
}
- (void)test_ViewDidLoadShouldCallGoogleTrends_getLatestTrends
{
[[googleTrends expect] getLatestTrends];
[vcSUT view]; // calls loadView
[googleTrends verify];
}
</code></pre>
<p>@end</p>
<p>Here's the VC:</p>
<pre><code>@implementation MWViewController {
NSArray *_trends;
}
@synthesize googleTrends;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_trends = [self.googleTrends getLatestTrends];
}
</code></pre>
<p>The googleTrends is a property in the header of course:</p>
<pre><code> @property (nonatomic, strong) MWGoogleTrends *googleTrends;
</code></pre>
<p>I would imagine it's being invoked because the following tests below it are passing:</p>
<pre><code>- (void)test_numRowsInTableViewShouldBeNumOfTrendsReturnedFromGetLatestTrends {
[vcSUT view];
int numSections = [vcSUT tableView:nil numberOfRowsInSection:0];
STAssertEquals(numSections, 3, @"should be 3 sections");
}
- (void)test_cellForRowAtIndexPath_should_return_cell_with_trendName_as_text {
[vcSUT view];
UITableViewCell *cell1 = [vcSUT tableView:nil cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
UITableViewCell *cell2 = [vcSUT tableView:nil cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
UITableViewCell *cell3 = [vcSUT tableView:nil cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:2]];
STAssertEquals(cell1.textLabel.text, @"trend1", @"cell text should be correct trend name");
STAssertEquals(cell2.textLabel.text, @"trend2", @"cell text should be correct trend name");
STAssertEquals(cell3.textLabel.text, @"trend3", @"cell text should be correct trend name");
}
@end
</code></pre>
<p>also getting this warning from the compiler, not sure if it related in any way:</p>
<pre><code>ld: warning: directory not found for option '-L/Users/markw/Projects/XCode/OReillyCasts/MWGoogleTrends/Pods/build/Release-iphoneos'
</code></pre>
| 3 | 1,079 |
React POST Request (MERN Stack)
|
<p>I am having trouble posting form data to MongoDB when testing on my local development environment. The endpoint that I am trying to post to is https://localhost:5000/users/add and I have been able to successfully post data to MongoDB using a REST API client and have also verified that my frontend is hooked up to my backend. I think there is something wrong with how I have setup my form, can someone please help? I am using axios library to send the request. Thank you in advance :)</p>
<p>package.json (client side code, I have set the proxy to https://localhost:5000/):</p>
<pre><code>{
"name": "my-app",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:5000/",
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.30",
"@fortawesome/free-solid-svg-icons": "^5.14.0",
"@fortawesome/react-fontawesome": "^0.1.11",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"axios": "^0.21.0",
"nodemon": "^2.0.6",
"react": "^16.13.1",
"react-datepicker": "^3.1.3",
"react-dom": "^16.13.1",
"react-hook-form": "^6.8.2",
"react-images-upload": "^1.2.8",
"react-modal": "^3.11.2",
"react-router-dom": "^5.2.0",
"react-scripts": "^3.4.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {}
}
</code></pre>
<p>ReactJS form:</p>
<pre><code>import React, { useState } from 'react';
import Modal from 'react-modal';
import Exit from '../cancel.svg';
import { useForm } from "react-hook-form";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEye } from "@fortawesome/free-solid-svg-icons";
import axios from "axios";
const eye = <FontAwesomeIcon icon={faEye} />;
Modal.setAppElement('#root')
const Register = () => {
const [modalIsOpen, setModalIsOpen] = useState (true)
const { register, handleSubmit, errors } = useForm ();
const [date, setDate] = useState(new Date("06/06/1994"));
const onSubmit = (data) => {data['birthdate']= date; console.log(data)};
const [firstName, setfirstName] = useState("");
const [lastName, setlastName] = useState("");
// const [birthdate, setbirthdate] = useState("");
const [gender, setGender] = useState("");
const [email, setemail] = useState("");
const [password, setpassword] = useState("");
const [city, setcity] = useState("");
const [passwordShown, setPasswordShown] = useState(false);
const togglePasswordVisiblity = () => {
setPasswordShown(passwordShown ? false : true);
};
const changeOnClick = e => {
e.preventDefault();
const users = {
firstName,
lastName,
date,
gender,
email,
password,
city
};
axios
.post("/users/add", users)
.then(res => console.log(res.data))
.catch(err => {
console.log(err);
});
};
return(
<Modal isOpen={modalIsOpen} onRequestClose={() => setModalIsOpen(false)} className='createBorder'>
<form onSubmit={changeOnClick} encType="multipart/form-data">
<div className='border-bottom'>
<img onClick= {() => setModalIsOpen(false)} src={Exit} className='exitButton-two' alt='X' />
<span className='create-an-account'>Create an account</span>
</div>
<div className='material' onSubmit={handleSubmit(onSubmit)}>
<p className='fieldsOne'>First name:</p>
<input onChange={e => setfirstName(e.target.value)} name='firstName' ref={register({required: true})} className='inputs' autoComplete='off'></input>
<p className='minifields'>This information will display on your profile</p>
{errors.firstName && <span className='registerRequired'>This field is required</span>}
<p className='fields'>Last name:</p>
<input onChange={e => setlastName(e.target.value)} name='lastName' ref={register({required: true})} className='inputs' autoComplete='off'></input>
<p className='minifields'>This information will display on your profile</p>
{errors.lastName && <span className='registerRequired'>This field is required</span>}
<p className='fields'>Birthdate:</p>
<DatePicker
ref={register({required: true})}
dateFormat="MM/dd/yyyy"
selected={date}
name='birthdate'
onChange={date => setDate(date)}
// onChange={e => setbirthdate(e.target.value)}
/>
<p className='minifields'>We'll use this information when considering what films you are qualified to test</p>
{errors.birthday && <span className='registerRequired'>This field is required</span>}
<p className='fields'>Gender</p>
<select name='Gender' ref={register({required: false})} className='inputs' onChange={e => setGender(e.target.value)}>
<option value="">Select...</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
<p className='minifields'>This information will display on your profile</p>
<p className='fields'>Email:</p>
<input onChange={e => setemail(e.target.value)} name='email' ref={register({required: true})} className='inputs' autoComplete='off'></input>
<p className='minifields'>We'll email you when films are for screening that fits your profile</p>
{errors.email && <span className='registerRequired'>This field is required</span>}
<div>
<p className='fields'>Password:</p>
<input onChange={e => setpassword(e.target.value)} type={passwordShown ? "text" : "password"} name='password' ref={register({required: true})} className='inputs' autoComplete='off'></input>
<i className='eye' onClick={togglePasswordVisiblity}>{eye}</i>
</div>
<p className='minifields'>You'll need one of these guys to sign in later.</p>
{errors.password && <span className='registerRequired'>This field is required</span>}
<p className='fields'>City:</p>
<input onChange={e => setcity(e.target.value)} name='city' ref={register({required: true})} className='inputs' autoComplete='off'></input>
<p className='minifields'>This information will display on your profile</p>
{errors.city && <span className='registerRequired'>This field is required</span>}
</div>
<div className='alignalign'>
{/* <button type='submit'>submit</button> */}
<a href='/GetStarted/completeProfile' onClick={handleSubmit(onSubmit)} type='submit' className='signupButton'>Sign Up</a>
</div>
</form>
</Modal>
)
}
export default Register;
</code></pre>
<p>Express BE:</p>
<pre><code>const express = require ("express");
const router = express.Router();
const Users = require("../models/users");
router.get('/', (req,res) => {
Users.find()
.then(user => res.json(user))
.catch(err => res.status(400).json(`Err: ${err}`));
});
//REQUEST TO ADD NEW USER
router.post('/add', (req, res) => {
const newUser = new Users({
firstName: req.body.firstName,
lastName: req.body.lastName,
birthdate: req.body.birthdate,
gender: req.body.gender,
email: req.body.email,
password: req.body.password,
city: req.body.password,
shareEmail: req.body.shareEmail,
filmmakerQuestion: req.body.filmmakerQuestion,
genres: req.body.genres,
favoriteFilms: req.body.favoriteFilms,
imbd: req.body.imbd,
portfolio: req.body.portfolio,
aboutYou: req.body.aboutYou,
})
newUser.save()
.then(() => res.json("The new User posted successfully!"))
.catch(err => res.status(400).json(`Error: ${err}`));
});
</code></pre>
| 3 | 5,066 |
Xamarin Http Requests only work on iOS Simulator
|
<p>I am using <code>system.net.http</code> to build a web service layer for my app. I started building this on an iphone simulator (as I develop for iOS first) and everything is working. I checked in my code and then started testing on other devices and nothing works... I get the same exception on a physical iOS device & android physical / emulator.</p>
<p>The Error I get is: <code>An error occurred while sending the request</code></p>
<p>Below is the code I am using to make the request. If I follow the code with breakpoints then it will fail on this line:
<code>var responce = await client.SendAsync(request);</code></p>
<pre><code>public class ApiService : IApiService
{
HttpClient client;
public List<Group> Groups { get; private set; }
public ApiService()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}
public async Task<List<Group>> GetGroupsForuser(int userId)
{
Groups = new List<Group>();
//GET http://{server}/groupcontrol/api/group/user/{userId}
var requestString = string.Format("{0}/{1}/{2}/{3}/{4}/{5}", Constants.BaseUrl, Constants.kControlURL, Constants.kEndpointAPI, Constants.kEndpointOot, Constants.kEndpointUser, userId);
var requestUri = new Uri(string.Format(requestString, string.Empty));
//Set method
var methodName = "GET";
var httpMethod = new HttpMethod(methodName.ToUpper());
//Create request
var request = new HttpRequestMessage(httpMethod, requestUri);
//Set Headers
request.Headers.Add("Accept", "application/x-www-form-urlencoded");
request.Headers.Add("Authorization", new Authorisation().getAuthToken());
Debug.WriteLine(string.Format("Printing out complete request: {0}", request));
try
{
var responce = await client.SendAsync(request);//client.SendAsync(requestMessage);
if (responce.IsSuccessStatusCode)
{
var content = await responce.Content.ReadAsStringAsync();
Groups = JsonConvert.DeserializeObject<List<Group>>(content);
} else {
Debug.WriteLine(string.Format("{0}",responce.StatusCode));
}
}
catch (Exception ex)
{
Debug.WriteLine(">>>ERROR-------------- {0}", ex.Message);
}
return Groups;
}
}
</code></pre>
<p>As stated before the code works on an iOS simulator but NOT a physical device (which is odd). I have updated the info.plist to use arbitrary loads so that shouldn't be an issue. The API I am talking too is being used in a native production iOS app (that I talk too with <code>NSURLSession</code>) so the API is not the problem, this is a xamarin issue. I have also given the Android app <code>Internet</code> permission.</p>
<p>Has anyone had any experience with this? It's extremely frustrating and I have no idea how to debug it further!</p>
| 3 | 1,118 |
Code wont work in browser but works in snippet tool
|
<p>I can get my code to work in the snippet tool, but once I try to run this in my own browser when I click on the $12 button, no alert will show up. Also, how can I get the alert to grab the header name so it displays "You have selected 1 gram of Skywalker". </p>
<p>The only buttons I have working so far are 12 and 35.
When a user selects a button, I want to alert them of the corresponding weight as well as the product name
<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>$(".btn1").click(function () {
var number = $(this).closest("tr").find(".weight1").text();
var name =$(this).closest("h3").find(".itemName").text();
alert("You have selected " + number + " of " + name);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Herb</title>
<link rel="stylesheet" type="text/css" href="all.css">
<!--<script src="herb.js"></script>-->
<script>
$(".btn1").click(function () {
var number = $(this).closest("tr").find(".weight1").text();
alert(number);
});
</script>
</head>
<body>
<div class="nav">
</div>
<div class="center">
<label for="show-menu" class="show-menu">Show Menu</label>
<input type="checkbox" id="show-menu" role="button">
<ul id="menu">
<li><a href="homepage.html">Home</a></li>
<li><a href="deals.html">Deals!</a></li>
<li>
<a href="#">Menu ↓</a>
<ul class="hidden">
<li><a href="herb.html">Herb</a></li>
<li><a href="concentrate.html">Concentrates</a></li>
<li><a href="edible.html">Edibles</a></li>
</ul>
</li>
<li>
<a href="#">Login ↓</a>
<ul class="hidden">
<li><a href="login.html">Login</a></li>
<li><a href="signup.html">Sign up</a></li>
</ul>
</li>
<li>
<a href="#">Social Media ↓</a>
<ul class="hidden">
<li><a href="https://www.facebook.com" target="_blank">Facebook</a></li>
<li><a href="https://www.snapchat.com/" target="_blank">Snapchat</a></li>
<li><a href="https://www.instagram.com" target="_blank">Instagram</a></li>
<li><a href="https://www.twitter.com" target="_blank">Twitter</a></li>
</ul>
</li>
</ul>
</div>
<div class="menuwrapper">
<div class="one">
<h3 class="itemName">Skywalker</h3>
<img src="Skywalker.png" alt="Skywalker" height="250" width="232">
<table>
<tr>
<td class="weight1">1 gram</td>
<td class="price"><input id="button1" class="btn1" type="button" value="$12"></td>
</tr>
<tr>
<td class="weight1">1/8 ounce</td>
<td class="price"> <input class="btn1" type="button" name="item1" value="$35"></td>
</tr>
<tr>
<td class="weight">1/4 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$75"></td>
</tr>
<tr>
<td class="weight">1/2 ounce</td>
<td class="price"> <input class="btn" type="button" name="item1" value="$140"></td>
</tr>
<tr>
<td class="weight">1 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$275"></td>
</tr>
</table>
</div>
<div class="two">
<h3>Purple Urkle</h3>
<img src="purple_urkle.jpg" alt="purple urkle" height="250" width="232">
<table>
<tr>
<td class="weight">1 gram</td>
<td class="price"> <input class="btn" type="button" name="item1" value="$10"></td>
</tr>
<tr>
<td class="weight">1/8 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$30"></td>
</tr>
<tr>
<td class="weight">1/4 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$70"></td>
</tr>
<tr>
<td class="weight">1/2 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$130"></td>
</tr>
<tr>
<td class="weight">1 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$250"></td>
</tr>
</table>
</div>
<div class="three">
<h3>Blueberry</h3>
<img src="Skywalker.png" alt="Blueberry" height="250" width="232">
<table>
<tr>
<td class="weight">1 gram</td>
<td class="price"><input class="btn" type="button" name="item1" value="$12"></td>
</tr>
<tr>
<td class="weight">1/8 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$35"></td>
</tr>
<tr>
<td class="weight">1/4 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$75"></td>
</tr>
<tr>
<td class="weight">1/2 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$140"></td>
</tr>
<tr>
<td class="weight">1 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$275"></td>
</tr>
</table>
</div>
<div class="four">
<h3>Lucid Blue</h3>
<img src="Skywalker.png" alt="Lucid blue" height="250" width="232">
<table>
<tr>
<td class="weight">1 gram</td>
<td class="price"><input class="btn" type="button" name="item1" value="$12"></td>
</tr>
<tr>
<td class="weight">1/8 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$35"></td>
</tr>
<tr>
<td class="weight">1/4 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$75"></td>
</tr>
<tr>
<td class="weight">1/2 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$140"></td>
</tr>
<tr>
<td class="weight">1 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$275"></td>
</tr>
</table>
</div>
<div class="five">
<h3>Strawberry Cough</h3>
<img src="Skywalker.png" alt="Strawberry cough" height="250" width="232">
<table>
<tr>
<td class="weight">1 gram</td>
<td class="price"><input class="btn" type="button" name="item1" value="$12"></td>
</tr>
<tr>
<td class="weight">1/8 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$35"></td>
</tr>
<tr>
<td class="weight">1/4 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$75"></td>
</tr>
<tr>
<td class="weight">1/2 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$140"></td>
</tr>
<tr>
<td class="weight">1 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$275"></td>
</tr>
</table>
</div>
<div class="six">
<h3>Cactus OG</h3>
<img src="Skywalker.png" alt="Cactus OG" height="250" width="232">
<table>
<tr>
<td class="weight">1 gram</td>
<td class="price"><input class="btn" type="button" name="item1" value="$12"></td>
</tr>
<tr>
<td class="weight">1/8 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$35"></td>
</tr>
<tr>
<td class="weight">1/4 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$75"></td>
</tr>
<tr>
<td class="weight">1/2 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$140"></td>
</tr>
<tr>
<td class="weight">1 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$275"></td>
</tr>
</table>
</div>
<div class="seven">
<h3>Critical Cure</h3>
<img src="Skywalker.png" alt="Critical Cure" height="250" width="232">
<table>
<tr>
<td class="weight">1 gram</td>
<td class="price"><input class="btn" type="button" name="item1" value="$12"></td>
</tr>
<tr>
<td class="weight">1/8 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$35"></td>
</tr>
<tr>
<td class="weight">1/4 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$75"></td>
</tr>
<tr>
<td class="weight">1/2 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$140"></td>
</tr>
<tr>
<td class="weight">1 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$275"></td>
</tr>
</table>
</div>
<div class="eight">
<h3>Green Crack</h3>
<img src="Skywalker.png" alt="Green Crack" height="250" width="232">
<table>
<tr>
<td class="weight">1 gram</td>
<td class="price"><input class="btn" type="button" name="item1" value="$16"></td>
</tr>
<tr>
<td class="weight">1/8 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$55"></td>
</tr>
<tr>
<td class="weight">1/4 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$95"></td>
</tr>
<tr>
<td class="weight">1/2 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$185"></td>
</tr>
<tr>
<td class="weight">1 ounce</td>
<td class="price"><input class="btn" type="button" name="item1" value="$350"></td>
</tr>
</table>
</div>
</div> <!--end container -->
</body>
</html></code></pre>
</div>
</div>
</p>
| 3 | 6,017 |
How to make card style menu in android
|
<p>I want to add card style in my app like this</p>
<p><a href="https://i.stack.imgur.com/OMzV9.png" rel="nofollow"><img src="https://i.stack.imgur.com/OMzV9.png" alt="enter image description here"></a></p>
<p>i use in my app mysql database so i need to make like this cards and put my data from database in it now i use ListView with this code</p>
<pre><code>public void listAllItme() {
ListAdapter lA = new listAdapter(listitems);
listView.setAdapter(lA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent open = new Intent(R_arabic.this, rewaya_show.class);
open.putExtra("name", listitems.get(position).name);
open.putExtra("url", listitems.get(position).url);
open.putExtra("img", listitems.get(position).img);
open.putExtra("num", listitems.get(position).num);
startActivity(open);
}
}
});
}
class listAdapter extends BaseAdapter {
ArrayList<listitem_gib> lista = new ArrayList<listitem_gib>();
public listAdapter(ArrayList<listitem_gib> lista) {
this.lista = lista;
}
@Override
public int getCount() {
return lista.size();
}
@Override
public Object getItem(int position) {
return lista.get(position).name;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item_gib, null);
TextView name = (TextView) view.findViewById(R.id.textView_gib);
ImageView img = (ImageView) view.findViewById(R.id.imageView_gib);
TextView num = (TextView) view.findViewById(R.id.textView_gib2);
TextView size = (TextView) view.findViewById(R.id.textView_gib3);
name.setText(lista.get(position).name);
num.setText(lista.get(position).num);
size.setText(lista.get(position).size);
Picasso.with(R_arabic.this).load("http://grassyhat.com/android/image/" + lista.get(position).img).into(img);
return view;
}
}
</code></pre>
<p>first i want to know how i can make like this card style</p>
<p>second how i can use this code with card menu not listview</p>
<p>sorry im new in android and sorry for my bad english</p>
| 3 | 1,078 |
Symfony2 Collection of Choises
|
<p>I'm making my first Symfony web app.
Now after creating a couple of forms I found some problem creating a form with a collection of choises.</p>
<p>Creating a collection of TextTypes is very easy and is working in a couple of my forms. Now when I create a collections of ChoiseTypes it does not show anything on the screen. After checking the html code it only show the select statement without any options. Also the prototype contains only the select and not the options.</p>
<p>Where is how I add the collections of choises to the form:</p>
<pre><code>->add('fieldTypes', CollectionType::class, array(
'entry_type' => ChoiceType::class,
'entry_options' => array(
'choices' => $fieldTypes,
'required' => true,
),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
))
</code></pre>
<p>And this is the twig part of the sollution:</p>
<pre><code><td>
<ul id="typeTable" data-prototype="{{ form_widget(form.fieldTypes.vars.prototype)|e }}">
{% for fieldType in form.fieldTypes %}
<li>
{{ form_widget(fieldType) }}
</li>
{% endfor %}
</ul>
</td>
</code></pre>
<p>And the full JS code:</p>
<pre><code><script type="text/javascript">
// keep track of how many email fields have been rendered
var nameCount = '{{ form.fieldNames|length }}';
var typeCount = '{{ form.fieldTypes|length }}';
var optionCount = '{{ form.fieldOptions|length }}';
jQuery(document).ready(function () {
jQuery('#add-new-field').click(function (e) {
e.preventDefault();
var nameList = jQuery('#nameTable');
var typeList = jQuery('#typeTable');
var optionList = jQuery('#optionTable');
// grab the prototype template
var newNameWidget = nameList.attr('data-prototype');
var newTypeWidget = typeList.attr('data-prototype');
var newOptionWidget = optionList.attr('data-prototype');
//var newTypeWidget = jQuery('#fieldType_prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your emails
// end name attribute looks like name="contact[emails][2]"
newNameWidget = newNameWidget.replace(/__name__/g, nameCount);
newTypeWidget = newTypeWidget.replace(/__name__/g, typeCount);
newOptionWidget = newOptionWidget.replace(/__name__/g, optionCount);
var $options = $("#fieldType_prototype > option").clone();
//$(newTypeWidget).append($options);
$("#form_fieldTypes_" + typeCount).html( $("#fieldType_prototype").html() );
// newTypeWidget.attr("id","form_fieldTypes_" + typeCount);
// newTypeWidget.attr('name', 'form[fieldTypes][' + typeCount + ']');
nameCount++;
typeCount++;
optionCount++;
// create a new list element and add it to the list
var newLi = jQuery('<li></li>').html(newNameWidget);
newLi.appendTo(nameList);
var newLi = jQuery('<li></li>').html(newTypeWidget);
newLi.appendTo(typeList);
var newLi = jQuery('<li></li>').html(newOptionWidget);
newLi.appendTo(optionList);
});
})
</script>
</code></pre>
<p>Variable $fieldTypes contains this:</p>
<pre><code>array('Text Field' => TextType::class,
'Text area' => TextareaType::class,
'Email' => EmailType::class,
'Number' => IntegerType::class,
'Url' => UrlType::class,
'Drop down' => ChoiceType::class,
'Date' => DateType::class,
'Checkbox' => CheckboxType::class);
}
</code></pre>
<p>Can someone help me with this issue?</p>
| 3 | 2,126 |
Why does my code make ID null
|
<p>I have a program that gets values from a database through a stored procedure. What it does is gets the values, downloads an image and then uploads it to a server. and after upload the run another stored procedure just to update the table to the new url.</p>
<p>Now it uploads a few images correct then all of a sudden it makes my ID = "" and I cant see why?</p>
<p>Result as log file:</p>
<pre><code>Property ID : 29140
pk_photo_id (TRY): 47334070
- File : propimage29140_9.jpg has been uploaded to AWS S3 bucket: ruans
Property ID : 30402
pk_photo_id (TRY): 47174447
Property ID : 29330
Property ID : `<-- why make it nothing`
pk_photo_id (TRY): 47174392
ERROR 6 : Cannot insert duplicate key row in object 'dbo.ET_EXPORT_PROPERTY_QUEUE' with unique index 'idx_pk'. The duplicate key value is (<NULL>).
The statement has been terminated.
</code></pre>
<p>My VB sub where this takes place:</p>
<pre><code>Dim files As String() = Directory.GetFiles(txtFolderPath)
'for each image get file name
For Each images As String In files
Dim id As String = ""
Dim photoID As String = ""
Dim position As String = ""
For Each str As String In IDS
If Path.GetFileNameWithoutExtension(sKey).Contains(str) Then
id = str
End If
Log("Property ID" & id)
For Each value As String In PhotoIDS
photoID = value
Next
For Each URL As String In fullURL
fullURLIndex = URL
Next
Next
'AWS upload
Try
utility.Upload(txtFolderPath & sKey, bucket)
Catch
needsToExitSub = True
Dim cmdSetError As New SqlCommand("ETSP_UPDATE_PHOTO_URLS")
cmdSetError.CommandType = CommandType.StoredProcedure
cmdSetError.Parameters.AddWithValue("@stype", "L")
cmdSetError.Parameters.AddWithValue("@surl", fullURLIndex)
cmdSetError.Parameters.AddWithValue("@status", 3)
cmdSetError.Parameters.AddWithValue("@pk_photo_id", photoID)
Log("pk_photo_id (CATCH): " & photoID)
cmdSetError.Parameters.AddWithValue("@bactive", 1)
cmdSetError.Parameters.AddWithValue("@property_id", id)
cmdSetError.Parameters.AddWithValue("@client_id", clientIDs)
conn.Open()
cmdSetError.Connection = conn
cmdSetError.ExecuteNonQuery()
Log(" - ERROR 4 : File : " & sKey & " Image ID : " & photoID & " Has NOT been uploaded to " & bucket & " , URL: " & fullURLIndex)
conn.Close()
If needsToExitSub = True Then
Exit Sub
End If
End Try
'Make files public - check this
Dim cannedACL As S3CannedACL = S3CannedACL.PublicRead
Dim fileNameOnly As String = Path.GetFileNameWithoutExtension(sKey)
Dim token As String = fileNameOnly.Remove(fileNameOnly.LastIndexOf("_"c))
Dim number As New String(token.SkipWhile(AddressOf [Char].IsLetter).ToArray())
'Run stored procudure and update if uploaded
Dim cmdSet As New SqlCommand("ETSP_UPDATE_PHOTO_URLS")
cmdSet.CommandType = CommandType.StoredProcedure
cmdSet.Parameters.AddWithValue("@stype", "L")
cmdSet.Parameters.AddWithValue("@surl", Convert.ToString("www.url.com/" & bucket & "/" & sKey))
cmdSet.Parameters.AddWithValue("@status", 2)
cmdSet.Parameters.AddWithValue("@pk_photo_id", photoID)
Log("pk_photo_id (TRY): " & photoID)
cmdSet.Parameters.AddWithValue("@bactive", 1)
cmdSet.Parameters.AddWithValue("@property_id", id)
cmdSet.Parameters.AddWithValue("@client_id", clientIDs)
conn.Open()
cmdSet.Connection = conn
cmdSet.ExecuteNonQuery()
conn.Close()
Next
Log(" - File : " & sKey & " has been uploaded to AWS S3 bucket: " & bucket)
Catch ex As System.NullReferenceException
Log("ERROR 5 : " & ex.Message)
Catch ex As Exception
Log("ERROR 6 : " & ex.Message)
Exit Try
End Try
</code></pre>
<p>So the images downloads file to my computer in the correct folder, then it uploads it also to the correct folder but then when it comes to update the database to update new url and the other parameters it gives the error, now i think it is because the <code>Property ID :</code> is made null.</p>
<p>Why would it get the correct <code>Property ID :</code> for lets say 8 images then get a null for a while and then again get the correct <code>Property ID :</code>. and how can i fix this.</p>
<p>C# help welcome</p>
| 3 | 2,454 |
SQL - How to combine 3 dates from 3 different tables (BigQuery)
|
<p>Need to have one view for each agent, and want to aggregate all dates to include all metrics</p>
<p><strong>Basic Information:-</strong></p>
<ul>
<li><p>In the <strong>productivity</strong> table carries the information like as follows:</p>
<pre><code> | Handled_DATE | Agent_Email | Handled | Missed
|:-----------: |:-------------: |:--------:|:------:|
|2013-11-05 | Agent_01@google.com | 80 | 9
|2013-11-06 | Agent_02@google.com | 60 | 15
|2013-11-07 | Agent_03@google.com | 70 | 7
|2013-11-08 | Agent_04@google.com | 55 | 13
|2013-11-09 | Agent_01@google.com | 73 | 5
|2013-11-10 | Agent_01@google.com | 64 | 14
</code></pre>
</li>
<li><p>In the <strong>Quality</strong> table carries the information like this:</p>
<pre><code> | Monitored_DATE | Agent_Email | Bussiness_Critical | Failed
|:-----------: |:-------------: |:-------------: |:-----------:|
|2013-11-05 | Agent_01@google.com | 2 | 2
|2013-11-06 | Agent_01@google.com | 1 | 1
|2013-11-07 | Agent_01@google.com | 4 | 4
|2013-11-08 | Agent_04@google.com | 1 | 1
</code></pre>
</li>
</ul>
<p>In the <strong>Absentieesm</strong> table it carries the information like this:</p>
<pre><code>| Attendance_Date | Agent_Email | Attendance | Late_min
|:-----------: |:-------------: |:----------:|:-----------:|
|2013-11-05 | Agent_01@google.com | Attend | 9
|2013-11-06 | Agent_01@google.com | Sick | 0
|2013-11-07 | Agent_01@google.com | Sick | 0
|2013-11-08 | Agent_04@google.com | 55 | 13
|2013-11-10 | Agent_01@google.com | Attend | 0
</code></pre>
<p><strong>Desired Output</strong></p>
<pre><code>| DATE | Agent_Email | Handled | Missed | Business_Critical | Failed |Attendance|Late_min
|:---------- |:-------------: |:-------:|:------:|:-----------------:|:-----: |:--------:|:------:|
|2013-11-05 | Agent_01@google.com | 80 | 9 | 2 | 2 | Attend | 9
|2013-11-06 | Agent_01@google.com | 0 | 0 | 1 | 1 | sick | 0
|2013-11-07 | Agent_01@google.com | 0 | 0 | 4 | 4 | sick | 0
|2013-11-08 | Agent_01@google.com | 0 | 0 | 0 | 0 | sick | 0
|2013-11-09 | Agent_01@google.com | 73 | 5 | 0 | 0 | NA | 0
|2013-11-10 | Agent_01@google.com | 64 | 14 | 0 | 0 | Attend | 0
</code></pre>
| 3 | 1,448 |
Add empty row if the condition is false
|
<p>Given the dataframe below:</p>
<pre><code> Row|Address_StoreHours_Phone_RemoveHrTag|
+---+------------------------------------+
| 1| Ph 148-01 Metro P...|
| 2| Store Hours: 7:00...|
| 3| <hr class="dashed"/>|
| 4| Ground Floor Vict...|
| 5| +632-82833778|
| 6| Store Hours:|
| 7| <hr class="dashed"/>|
| 8| Phase 1 Package 1...|
| 9| +632-83722847|
| 10| Store Hours: 7:00...|
| 11| <hr class="dashed"/>|
</code></pre>
<p>How do i add empty row 1 row above hr class="dashed"/ if hr class="dashed"/'s row is not divisible by 4, e.g.</p>
<pre><code> Row|Address_StoreHours_Phone_RemoveHrTag|
+---+------------------------------------+
| 1| Ph 148-01 Metro P...|
| 2| |
| 3| Store Hours: 7:00...|
| 4| <hr class="dashed"/>|
| 5| Ground Floor Vict...|
| 6| +632-82833778|
| 7| Store Hours:|
| 8| <hr class="dashed"/>|
| 9| Phase 1 Package 1...|
| 10| +632-83722847|
| 11| Store Hours: 7:00...|
| 12| <hr class="dashed"/>|
</code></pre>
<p>Here's what i've done so far, hr_tag column returns true if hr class="dashed"/ is in row divisible by 4</p>
<pre><code>spark.sql("""
WITH create_row AS(
SELECT CAST(ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS INTEGER) AS Row, *
FROM ssd_others
), filter_hr_tag AS (
SELECT
*,
CASE
WHEN `Address_StoreHours_Phone_RemoveHrTag` = '<hr class="dashed"/>' AND `Row` % 4 = 0
THEN True
ELSE False
END AS hr_tag
FROM create_row
)
SELECT *
FROM filter_hr_tag
""")
</code></pre>
<p>and here's the code's output</p>
<pre><code>Row|Address_StoreHours_Phone_RemoveHrTag|hr_tag|
+---+------------------------------------+------+
| 1| Ph 148-01 Metro P...| false|
| 2| Store Hours: 7:00...| false|
| 3| <hr class="dashed"/>| false|
| 4| Ground Floor Vict...| false|
| 5| +632-82833778| false|
| 6| Store Hours:| false|
| 7| <hr class="dashed"/>| false|
| 8| Phase 1 Package 1...| false|
| 9| +632-83722847| false|
| 10| Store Hours: 7:00...| false|
| 11| <hr class="dashed"/>| false|
</code></pre>
| 3 | 1,683 |
How to open another python file from tkinter in a specific condition(like user wins)
|
<p>According to my advisor, she wants me to give a more fancy window when the user wins. I asked whether there is a way to play gif on stack overflow before, and there is a way according to some people. Now I have finished writing the script for the gif which is going to play (actually I referred that from a website because my ability is limited):</p>
<pre><code>import tkinter as tk
from PIL import Image, ImageTk
from itertools import count, cycle
class ImageLabel(tk.Label):
def load(self, im):
if isinstance(im, str):
im = Image.open(im)
frames = []
try:
for i in count(1):
frames.append(ImageTk.PhotoImage(im.copy()))
im.seek(i)
except EOFError:
pass
self.frames = cycle(frames)
try:
self.delay = im.info['duration']
except:
self.delay = 100
if len(frames) == 1:
self.config(image=next(self.frames))
else:
self.next_frame()
def unload(self):
self.config(image=None)
self.frames = None
def next_frame(self):
if self.frames:
self.config(image=next(self.frames))
self.after(self.delay, self.next_frame)
root = tk.Tk()
lbl = ImageLabel(root)
lbl.pack()
lbl.load('D:/Personal/Game/Win.gif')
root.mainloop()
</code></pre>
<p>Now I have seen that a class is defined, so can I add the class in <code>showframe</code> like <code>controller.showframe(ImageLabel)</code>?<br />
The code for the last question:</p>
<pre><code>class Q10(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="MCQ test!!! Does group or period in the periodic table represent outer shell "
"electrons?",
font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Period",
command=lambda: [self.correspondingBehavior("Wrong...You can draw it out and see"),
controller.show_frame(Failure), fail7()])
button1.pack()
button2 = tk.Button(self, text="Group",
command=lambda: controller.show_frame(Success)) # Can I add the imagelabel class here?
button2.pack()
button3 = tk.Button(self, text="Quit", command=lambda: [controller.show_frame(Credits), give_up()])
button3.pack()
def correspondingBehavior(self, choice):
print(choice)
</code></pre>
| 3 | 1,146 |
Putting the value of a variable from class to the variable of my form
|
<p>I have a class names <code>intersection_regular_island</code> and I created a new instance of it in <code>form1</code>. I wanted to re-declare a certain variable in that class so I tried this code</p>
<pre><code>Public Class form1
Dim a As New intersection_regular_island
Dim penToUse As Pen = a.leftA_pen
Sub sampleSub()
penToUse = New Pen(Color.Green, a.arrowWidth)
End Sub
End Class
</code></pre>
<p>Whereas if I do it like this, it is working</p>
<pre><code>Public Class form1
Dim a As New intersection_regular_island
Sub sampleSub()
a.leftA_pen = New Pen(Color.Green, a.arrowWidth)
End Sub
End Class
</code></pre>
<p>Note that it is just a small part of the code, it's not the actual code. It is for illustration purposes so maybe I might missed something.</p>
<p>Seems like I'm missing something that is so simple?</p>
<p>Edit:</p>
<p>I want to do it like that so I can easily perform a <code>select case</code></p>
<p>So instead of copying and pasting this code many times</p>
<pre><code>Select Case lightFunctionNum
Case 1
a.leftA_pen = New Pen(Color.Green, a.arrowWidth)
Case 2
a.leftA_pen = New Pen(Color.Yellow, a.arrowWidth)
Case 3
a.leftA_pen = New Pen(Color.Red, a.arrowWidth)
Case 4
Dim blinkColorTrue As Color = Color.Green
Dim blinkColorFalse As Color = Color.Transparent
If blinkBoolean_A = False Then a.leftA_pen = New Pen(blinkColorFalse, a.arrowWidth) : blinkBoolean_A = True Else a.leftA_pen = New Pen(blinkColorTrue, a.arrowWidth) : blinkBoolean_A = False
Case 5
Dim blinkColorTrue As Color = Color.Yellow
Dim blinkColorFalse As Color = Color.Transparent
If blinkBoolean_A = False Then a.leftA_pen = New Pen(blinkColorFalse, a.arrowWidth) : blinkBoolean_A = True Else a.leftA_pen = New Pen(blinkColorTrue, a.arrowWidth) : blinkBoolean_A = False
Case Else
a.leftA_pen = New Pen(Color.Transparent, a.arrowWidth)
End Select
</code></pre>
<p>I wanted it become like this</p>
<pre><code>Select Case arrowAndPosition
Case arrowAndPositionChoices.A_Left
penToUse = a.leftA_pen
Case arrowAndPositionChoices.B_Left
penToUse = a.leftB_pen
Case arrowAndPositionChoices.C_Left
penToUse = a.leftC_pen
Case arrowAndPositionChoices.D_Left
penToUse = a.leftD_pen
End Select
Select Case lightFunctionNum
Case 1
penToUse = New Pen(Color.Green, a.arrowWidth)
Console.WriteLine("Trigger")
Case 2
penToUse = New Pen(Color.Yellow, a.arrowWidth)
Case 3
penToUse = New Pen(Color.Red, a.arrowWidth)
Case 4
Dim blinkColorTrue As Color = Color.Green
Dim blinkColorFalse As Color = Color.Transparent
If blinkBoolean = False Then penToUse = New Pen(blinkColorFalse, a.arrowWidth) : blinkBoolean = True Else penToUse = New Pen(blinkColorTrue, a.arrowWidth) : blinkBoolean = False
Case 5
Dim blinkColorTrue As Color = Color.Yellow
Dim blinkColorFalse As Color = Color.Transparent
If blinkBoolean = False Then penToUse = New Pen(blinkColorFalse, a.arrowWidth) : blinkBoolean = True Else penToUse = New Pen(blinkColorTrue, a.arrowWidth) : blinkBoolean = False
Case Else
penToUse = New Pen(Color.Transparent, a.arrowWidth)
End Select
</code></pre>
| 3 | 1,528 |
Linux - Extract core utilization for a single process to a file
|
<p>I am trying to figure out how to extract the cpu core utilization for a SINGLE process in linux and parse it. I know that I can get the overall core utilization via top and then press "1". I am already able to parse that. However, now I want to do the same thing for a single process. I tried it with ps and calculating the core utilization myself but I am not so sure if my script is accurate enough, something seems off. (Note that this version calculates overall core utilization since it is WIP) I get errors like this after a while in my terminal: </p>
<blockquote>
<p>test.sh: line 31: +: syntax error: operand expected (error token is
"+")</p>
</blockquote>
<p>I cannot figure out why this error just randomly occurs.</p>
<pre><code>#!/bin/env bash
read -p "Enter PID to observe:" pid
run=false
ps -p $pid -L -o cputime,etime,psr,pcpu
for (( u = 1 ; u <= 100 ; u++ ))
do
lines=$(ps -p $pid -L -o psr,pcpu | awk 'END{print NR}')
for (( i=1; i<=$lines; i++))
do
core=$(ps -p $pid -L -o psr,pcpu | awk 'NR=='$i'{print $1}')
if [ $run == false ]
then cpuTimeS=+$(ps -p $pid -L -o cputime,etime | awk 'NR=='$i'{print $1}' | awk -F : '{ printf("%.2f\n", $1*60+$2*60+$3); }')
elapsedTimeS=+$(ps -p $pid -L -o cputime,etime | awk 'NR=='$i'{print $2}' | awk -F : '{ printf("%.2f\n", $1*60+$2*60+$3); }')
cpuTimeSi=${cpuTimeS%.*}
elapsedTimeSi=${elapsedTimeS%.*}
cpuTimeSiResult=$(( cpuTimeSi + cpuTimeSiResult ))
elapsedTimeSiResult=$(( elapsedTimeSi + elapsedTimeSiResult ))
else
cpuTimeE=+$(ps -p $pid -L -o cputime,etime | awk 'NR=='$i'{print $1}' | awk -F : '{ printf("%.2f\n", $1*60+$2*60+$3); }')
elapsedTimeE=+$(ps -p $pid -L -o cputime,etime | awk 'NR=='$i'{print $2}' | awk -F : '{ printf("%.2f\n", $1*60+$2*60+$3); }')
cpuTimeEi=${cpuTimeE%.*}
elapsedTimeEi=${elapsedTimeE%.*}
cpuTimeEiResult=$(( cpuTimeEi + cpuTimeEiResult ))
elapsedTimeEiResult=$(( elapsedTimeEi + elapsedTimeEiResult ))
fi
done
if [ "$run" = true ]
then result=$( echo "scale=2; ($cpuTimeEiResult - $cpuTimeSiResult) / ($elapsedTimeEiResult - $elapsedTimeSiResult) * 100.0" | bc)
echo "RESULT:" $result
echo "cpuTimeSTART:" $cpuTimeSiResult
echo "elapsedTimeSTART:" $elapsedTimeSiResult
echo "cpuTimeEND:" $cpuTimeEiResult
echo "elapsedTimeEND:" $elapsedTimeEiResult
fi
sleep 1
if [ "$run" = false ]
then run=true
else
run=false
fi
done
</code></pre>
<p>Are there any ideas on how I could solve this better?</p>
<p>I am glad for any advice</p>
| 3 | 1,197 |
Limit clicks on button based on user role
|
<p>I have a restricted page with entries for only-members in WordPress, and on this page there is a "View more" button for each entry. I'm looking for a solution, to limit clicks for that specific button depending on which user role the user has assigned. The button has its own class ".se-mere-knap".</p>
<p>For example user role 1 needs to have 5 clicks on this button from the time the subscription was created. If they reach the limit of clicks, they are not able to access any entries anymore by clicking the button. The subscriptions run for a month, and there are different unique users, so it needs to reset for that specific user when 30 days have passed from the start of their subscription.</p>
<p>I've made the code, based on user roles, for enqueue of the script to load the .js files in child theme functions.php:</p>
<pre><code> function add_custom_script_1() {
if ( current_user_can( 'um_5-klik-test' ) ) {
wp_register_script('custom_script_1', home_url() . '/button-restrict/button-restrict-5.js', array( 'jquery' ));
wp_enqueue_script('custom_script_1');
}
}
add_action( 'wp_enqueue_scripts', 'add_custom_script_1', 999);
</code></pre>
<p>Secondly, wiht help from @Digi Coder, the button-restrict-5.js is as following:</p>
<pre><code>"use strict";
viewmore_settings();
// checks if the expiry date has elapsed
function check_viewmore_expiry() {
// set the current date
var curDate = new Date().getTime();
// get the difference between the expiry date and current date
var distance = localStorage.expDate - curDate;
// round up to get the exact date remaining
var days = Math.floor( distance / ( 1000 * 60 * 60 * 24 ) );
// log remaining date to the console
console.log( days + ' days left.' );
// check if the expiry date has elapsed
if ( distance < 0 ) {
// log expiry message to the console
console.log( 'Time Expired.' );
// reset the expiry date to 30 days
localStorage.expDate = new Date().setUTCSeconds( 60 * 60 * 24 * 30 );
// reset the counter to zero
localStorage.counter = 0;
}
}
// disables view more button if counter limit is reached
function viewmore_button_disabled() {
// the html button that user clicks
var btn = document.querySelector( 'button.se-mere-knap' );
// check if user click action is up to five or greater than five
if ( Number( localStorage.counter ) >= 5 ) {
// disable the button
btn.disabled = true;
// button is disabled
return true;
}
// button is not disabled
return false;
}
// Sets value for the counter and expiry date stored in local storage
function viewmore_settings() {
// check for local storage support
if ( typeof Storage !== 'undefined' ) {
// check if counter is not set in storage
if ( localStorage.counter === undefined ) {
// set counter to zero
localStorage.counter = 0;
}
// check if expDate is not set in storage
if ( localStorage.expDate === undefined ) {
// set expiry date to 30 days
localStorage.expDate = new Date().setUTCSeconds( 60 * 60 * 24 * 30 );
}
// check if the expiry date has elapsed
check_viewmore_expiry();
// disable view more button if counter limit is reached
viewmore_button_disabled();
} else {
// display message for browsers that does not support storage
window.alert( 'Din browser understøtter desværre ikke vores funktioner.' );
}
}
// runs when user clicks the view more button
function viewmore_func() {
// check for local storage support
if ( typeof Storage !== 'undefined' ) {
// check if the expiry date has elapsed
check_viewmore_expiry();
// check if the view more button is disabled
if ( viewmore_button_disabled() ) {
// display alert message for maximum click attempt
window.alert( 'Din grænse for antal klik ind på en jobsøgendes profil er nået. Du kan opgradere til flere klik, gennem din virksomhedsprofil. Antal af klik bliver nulstillet hver 30. dag.' );
} else {
// increment counter for every user click action
localStorage.counter = Number( localStorage.counter ) + 1;
// log the counter value to console
console.log( localStorage.counter );
// redirect user to resource page or show user the content
window.location.assign( 'index.php' );
}
}
}
document.querySelector( 'button.se-mere-knap' ).addEventListener( 'click', viewmore_func );
</code></pre>
<p>I've created a user with this role to test with, but it doesn't work. Nothing happens when i exceed the limit of 5 click. No limit of clicks are set.</p>
| 3 | 2,005 |
autokriging and SpatialPixel grid file
|
<p>I am trying to use autoKrige in automap package.
My data looks like</p>
<pre><code>head(LL12)
Location Longitude Latitude percent
1 L1 16.48476 -28.60737 1.0000000
2 L3 16.90045 -29.24154 1.0000000
3 L4 16.99268 -28.44906 0.6363636
4 L5 17.06871 -29.67825 1.0000000
5 L6 17.09935 -29.00169 0.6000000
6 L7 17.25630 -28.82418 1.0000000
</code></pre>
<p>and I am trying to plot this in a South African map.</p>
<p>First I obtained the grid following <a href="https://stackoverflow.com/questions/43436466/create-grid-in-r-for-kriging-in-gstat">Create Grid in R for kriging in gstat</a></p>
<pre><code>SAgrd <- makegrid(SApol_border, n = 1000)
colnames(SAgrd) <- c('lon','lat')
SAgrd_pts <- SpatialPoints(coords = SAgrd,
proj4string=CRS(proj4string(SApol_border)))
SAgrd_pts_in <- SAgrd_pts[SApol_border, ]
plot(SAgrd_pts_in)
plot(SAgrd_pts_in)
</code></pre>
<p><a href="https://i.stack.imgur.com/B4qyP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B4qyP.png" alt="enter image description here" /></a></p>
<p>then I convert it to a SpatialPixel dataframe</p>
<pre><code>SAgrd_pts_in = as(SAgrd_pts_in,"SpatialPixelsDataFrame")
</code></pre>
<p>but <code>plot(SAgrd_pts_in)</code> gives the follwoing error message:</p>
<blockquote>
<p>Error in .subset2(x, i, exact = exact) : subscript out of bounds</p>
</blockquote>
<p>and when I want to use the following line in autokriging also gives error message</p>
<pre><code>krigLL12_fit <- autoKrige(percent~1, SA.grid, LL12spdf) # percent is the variable of interest in the spdf LL12spdf
</code></pre>
<p>error message:</p>
<blockquote>
<p>Error in autoKrige(percent ~ 1, SA.grid, LL12spdf) :
Either input_data or new_data is in LongLat, please reproject.
input_data: +proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs
new_data: NA
In addition: Warning messages:
1: In proj4string(input_data) :
CRS object has comment, which is lost in output
2: In proj4string(input_data) :
CRS object has comment, which is lost in output
3: In showSRID(uprojargs, format = "PROJ", multiline = "NO") :
Discarded datum Unknown based on WGS84 ellipsoid in CRS definition,
but +towgs84= values preserved</p>
</blockquote>
<p>I am very new in this topic and cannot realize what I need to do, or what to correct, the coordinate units look the same in the grid and in the data file. I also fitted an autovariogram and tried to use in in autokrige but it doean't work either. thnx.</p>
| 3 | 1,067 |
How to create foreach loop value dynamically table mpdf?
|
<p>I am beginner PHP developer. I'm using mPDF library and I'm trying to write a code which will create multiple table value showing. The problem is that always only the first value only showing.</p>
<p>I can't figure out how to solve this. Would someone lead me on the right path? My logic is:</p>
<ul>
<li>I have one array with all of orders; for each order I would like to create PDF. </li>
<li>I loop the array and each time call the MPDF library </li>
</ul>
<p>Code:</p>
<pre><code><?php
require_once "clientinvoice.php";
$inNumber = $record['ginvo_client_invoice_no'];
$count = 0;
$index = 0;
foreach ($invoices as $invoice) {
$count+=$invoice['rate_with_vat'];
}
$invAmount = number_format((float)$count, 2, '.', '');
//vendor name generate
if ($_GET['showVendor']==1) {
foreach ($vendorDetails as $vendorDetail) {
if($vendorDetail['id']==$invoice['vendor_id']){
$vendor_name = $vendorDetail['first_name'];
$address_treet = $vendorDetail['address_street'];
$address_city = $vendorDetail['address_city'];
$address_state = $vendorDetail['address_state'];
$address_country =$vendorDetail['address_country'];
$postal_cod = $vendorDetail['address_postalcode'];
}
}
$vendorAddress = $vendor_name .','. $address_treet.','. $address_city.','. $address_state.','. $address_country.','. $postal_cod;
$tdClass = 'vendorDt';
}else {
$vendorAddress = '';
$tdClass = '';
}
//proforma invoice display
if ($proforma_invoice_amount>0&&$record['proforma_invoice_c'] == 'yes') {
$profomaAmount = number_format((float)$proforma_invoice_amount, '2', '.', '');
$resttoPay = $count - $profomaAmount;
$restPay = number_format((float)$resttoPay, '2', '.', '');
$proTrClass = '';
}else {
$proTrClass = 'proformaFooter';
}
if ($record['client_location_c'] == 'germany') {
$thanks = '<p>Thank you for your order';
$footerAddress = '<tr><td colspan="7" style="display:flex;justify-content:space-between;"><div class="manufacture-address"><div class="display-flex" style="text-align:center">
<div class="text-left" style="width:33%">
<p>
<span>Global Guide Services GmbH</span><br>
<span>Münchner Str. 23</span><br>
<span>D-83703 Gmund a. Tegernsee</span><br>
<span>Local Court Munich, HRB 223121</span>
</p>
</div>
<div class="text-center" style="text-align:center;width:33%;position:absolute;bottom:0px;margin-left:60%;margin-top:-12%;">
<p>
<span>Managing Director: Siavash Sartipi</span><br>
<span><i class="fa fa-phone"></i> +49 151 74327305</span><br>
<span><i class="fa fa-print"></i> +49 721 509663197</span><br>
<span>www.global-guide-services.com</span>
</p>
</div>
<div class="text-right" style="text-align:center;width:33%;position:absolute;bottom:0;right:10px;margin-top:-12%;" >
<p>
<span>VAT Nr DE 305563525</span><br>
<span>Tax Nr 139/127/50609</span><br>
<span>IBAN DE41 7001 0080 0697 1208 00</span><br>
<span>BIC/SWIFT PBNKDEFF</span>
</p>
</div>
</div></div></td></tr>';
}else {
$thanks = '<p>Intocmit de: Andreea loana</p><br/>
<div class="cnp"><span>CNP: 2950318151935</span></div>';
$footerAddress = '<tr><td colspan="7" style="text-align:center;"><div class="manufacture-address"><div class="text-center address_Raif" style="text-align:center">
<p>
<span>Account holder: <label>Global Guides Services SRL,</label> Bank:Raiffeisen</span><br>
<span>IBAN RO 92 RZBR 0000 0600 1754 9626 BIC(SWIFT):RZBRROBU</span><br>
<span>VAT: RO34622172</span><br>
</p>
</div></div></td></tr>';
}
//footer address display
$html = '
<html>
<head>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
body {
font-family: Arial, Verdana, Helvetica, sans-serif !important;
font-size: 14px !important;
background: #efefef;
-webkit-print-color-adjust: exact;
width: 960px;
line-height:1 !important;
margin: 0 auto;
}
table.report {
border-collapse: collapse;
width: 100%;
}
.invoice-head h3 {
text-transform: uppercase;
margin-bottom: 0;
font-size: 16px;
word-spacing: -2px;
padding: 5px;
}
p { margin: 0pt; }
// table.items {
// border: 0.1mm solid #000000;
// }
td { vertical-align: top; }
// .items td {
// border-left: 0.1mm solid #000000;
// border-right: 0.1mm solid #000000;
// }
table thead td { background-color: #EEEEEE;
text-align: center;
// border: 0.1mm solid #000000;
font-variant: small-caps;
}
.items td.blanktotal {
background-color: #EEEEEE;
border: 0.1mm solid #000000;
background-color: #FFFFFF;
border: 0mm none #000000;
border-top: 0.1mm solid #000000;
border-right: 0.1mm solid #000000;
}
.items td.totals {
text-align: right;
border: 0.1mm solid #000000;
}
.items td.cost {
text-align: "." right;
}
.headerBorder{
border-bottom:3px solid #344d90;
}
.invoice-head {
text-align: center;
position: relative;
}
.invoice-head .invoice_head-bg {
height: 61px;
position: absolute;
z-index: -1;
width: 100%;
background: #d4d2d2;
-webkit-print-color-adjust: exact;
}
.img-gradient {
position: absolute;
right: 39px;
top: 0;
height: 250px;
width: 200px;
z-index: -1;
background: #bdc9ec;
background: -webkit-linear-gradient(#bdc9ec, rgba(107, 113, 181, 0));
background: -o-linear-gradient(#bdc9ec, rgba(107, 113, 181, 0));
background: -moz-linear-gradient(#bdc9ec, rgba(107, 113, 181, 0));
background: linear-gradient(#bdc9ec, rgba(107, 113, 181, 0));
-webkit-print-color-adjust: exact;
}
.topRight{
position:absolute;
right:60px;
top:3%;
}
.table-header th, .table-body td, .table-footer td {
padding: .70rem;
vertical-align: top;
border-top: 1px solid #eceeef;
width: 13%;
}
.text-right {
text-align: right;
font-style: initial;
}
.vendorDt{
background-color: rgba(123, 159, 234, 0.26);-webkit-print-color-adjust: exact;
}
.footer{
background: #a9b8e2;-webkit-print-color-adjust: exact;margin-top: -20% !important;margin-bottom: 50% !important;
}
.footer td{
text-transform:uppercase;text-align:right;
}
.proformaFooter{
display:none;
}
.manufacture-address {
text-align: center;
}
.invoice-details {
display: flex;
}
</style>
</head>
<body>
<!--mpdf
<htmlpageheader name="myheader">
<table width="100%" class="report">
<tr>
<td><img src="images/company_logo.png" alt="" style="width:150px"></td>
</tr></table>
<div class="headerBorder"></div>
</htmlpageheader>
<htmlpagefooter name="myfooter">
<div style="border-top: 1px solid #344d90; text-align: center; padding-top: 1mm; ">&nbsp;</div>
<table width="100%" class="report">
<tbody>'.$footerAddress.'</tbody>
</table>
</htmlpagefooter>
<sethtmlpageheader name="myheader" value="on" show-this-page="1" />
<sethtmlpagefooter name="myfooter" value="on" />
mpdf-->
<div class="img-gradient">&nbsp;</div>
<table width="100%" style="font-family: arial;" cellpadding="0">
<tbody>
<tr>
<td colspan="3">
<div class="address-left">
<p><strong>client.invoice@global-guide-services.com</strong></p><br/>
<span>'.$record['client_name'].'</span><br>
<span>'.$record['client_address'].'</span><br>
<span>'.$record['client_address_city'].'</span><br>
<span>'.$record['client_address_state'].', '.$record['client_address_country'].'</span><br>
<span>'.$record['client_address_postalcode'].'</span><br>
<span style="font-weight:bold;margin-top:25px;">'.$clientvatId.'</span>
</div></td>
<td colspan="4" style="text-align:right">
<div class="topRight"><h3>'.$country.'</h3></div>
<div class="address-right">
<p>'.$address.'</p>
<p>
<span><i class="fa fa-phone '.$phone.'"></i>'.$record['recipient_phone_number_c'].'</span><br>
<span><i class="fa fa-print '.$fax.'"></i>'.$record['recipient_fax_number_c'].'</span>
</p>
</div></td>
</tr>
<tr><td colspan="7" style="margin-bottom:2px;"></tr>
</tbody>
<br />
<tbody>
<tr>
<div class="invoice_head-bg" style="background-color:#ccc;height:25px"></div>
<td colspan="7" style="line-height:1.50;margin-top:10% !important;text-align:center;position:relative;-webkit-print-color-adjust: exact;background-color:#ccc;">
<div class="invoice-head">
<h3 style="text-transform: uppercase;margin-bottom:0;font-size:13px;word-spacing:-2px;padding:5px;">'.$invoice_title.'</h3>
<p style="margin-top: 25px;font-size: 14px;word-spacing: 4px;">for the assignment of guided tours, assistances, tour escorts, transfers</p>
</div>
</td>
</tr>
<br />
<tr>
<td colspan="7" style="display: flex;line-height:1.75;">
<div class="invoice-details">
<div class="invoice-number">
<p><strong>Invoice number :</strong> <span>'.$record['ginvo_client_invoice_no'].'</span></p>
<p><strong>Invoice date :</strong> <span>'.$inv_date.'</span></p>
</div>
<div class="invoice-info" style="position:absolute;right:7%;top:31%;">
<span>(please invoice number and date with your payment)</span>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<br />
<table class="items" width="100%" style="" cellpadding="8" cellspacing="0">
<thead>
<tr style="background: #7d93ce;">
<th>Group Id</th>
<th>Date</th>
<th>City</th>
<th>Service</th>
<th>Duration</th>
<th>Note</th>
<th>Rate &euro;</th>
</tr>
</thead>
<tbody>
<tr>
<td>'.$invoice['group_id'].'</td>
<td>'.$invoice['service_date'].'</td>
<td>'.$invoice['city'].'</td>
<td>'.$invoice['service'].'</td>
<td>'.$invoice['duration'].'</td>
<td>'.$invoice['notes'].'</td>
<td class="cost">&euro; '.$invoice['rate_with_vat'].'</td>
</tr>
<tr class='.$tdClass.'>
<td colspan="7" style="text-align:center">'.$vendorAddress.'</td>
</tr>
<!-- END ITEMS HERE -->
<tr class="footer">
<td class="text-right" colspan="6"><strong>Total Sum</strong></td>
<td class="text-right"><b>&euro; '.$invAmount.'</b></td>
</tr>
<div class="'.$proTrClass.'">
<tr class="footer">
<td class="text-right" colspan="6"><strong>Paid with Proforma</strong></td>
<td class="text-right"><b>&euro; '.$profomaAmount.'</b></td>
</tr>
<tr class="footer">
<td class="text-right" colspan="6"><strong>Rest to Pay</strong></td>
<td class="text-right"><b>&euro; '.$restPay.'</b></td>
</tr>
</div>
</tbody>
<tbody>
<tr>
<td colspan="7" style="text-align:right">
<div class="vat text-right">
<span>'.$reverse.'</span>
</div>
</td>
</tr>
<tr>
<td colspan="7">
<div class="invoice-include">
<p>'.$content.'</p>
</div>
</td>
</tr>
<tr>
<td colspan="7">
<div class="invoice-dueDate"><p>Our invoice falls due immediately and is to be paid in full within</p>
<div class="date"><span style="margin: 15px 40px;position:relative;right:10px;">'.$due_date.'</span></div>
</div>
</td>
</tr>
<tr>
<td colspan="7">
<div class="thanks">'.$thanks.'</div>
</td>
</tr>
</tbody>
</table>
</body>
</html>
';
//==============================================================
//==============================================================
//==============================================================
//==============================================================
//==============================================================
//==============================================================
define('_MPDF_PATH','../custom/mpdf/');
include("../custom/mpdf/mpdf.php");
$mpdf=new mPDF('c','A4','','',10,10,29,35,10,5);
$mpdf->SetProtection(array('print'));
$mpdf->SetTitle($inNumber);
$mpdf->SetAuthor("Venkatesh");
$mpdf->showWatermarkText = true;
$mpdf->watermark_font = 'DejaVuSansCondensed';
$mpdf->watermarkTextAlpha = 0.1;
$mpdf->SetDisplayMode('fullpage');
$mpdf->WriteHTML($html);
$mpdf->Output($inNumber.'.pdf', 'I'); exit;
exit;
?>
</code></pre>
| 3 | 6,864 |
Fluent NHibernate Many to Many insert issue
|
<p>I have UserModel and RoleModel. I thinked thay may be in many to many relationship 'cause Users can have more than one role and a role can has more than one User. I make it Many to many but when i try insert a user i'm getting error like:</p>
<blockquote>
<p>INSERT statement FOREIGN KEY constraint "FK6209393F7EB4E792" coincided with. "projectcoderwho" database "dbo.roles" column 'Id' There was an overlap in the table.
The statement has been terminated.</p>
</blockquote>
<p>I search it some but nothing usefull for me or I can't see the somethings.
Now has anyone an idea about my problem?</p>
<p>This codes worked only one time. But now I'm getting the error which above.</p>
<p>UserModel.cs:</p>
<pre><code>public class UserModel
{
public virtual int Id { get; set; }
public virtual DateTime RegisterDate { get; set; }
public virtual string RegisterIp { get; set; }
public virtual string EMail { get; set; }
public virtual string Password { get; set; }
public virtual string UserName { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string WebSiteLink { get; set; }
public virtual string FaceBookLink { get; set; }
public virtual string TwitterLink { get; set; }
public virtual string GooglePlusLink { get; set; }
public virtual string PinterestLink { get; set; }
public virtual IList<RoleModel> UserRole { get; set; }
public virtual DateTime LastLogIn { get; set; }
public virtual string LastLoginIP { get; set; }
public virtual string About { get; set; }
public virtual bool IsActive { get; set; }
public virtual bool IsFreelancer { get; set; }
public virtual bool IsBanned { get; set; }
public UserModel()
{
UserRole = new List<RoleModel>();
}
}
</code></pre>
<p>RoleModel.cs</p>
<pre><code>public class RoleModel
{
//will contains as default: Admin,Moderator,Author,User
public virtual int Id { get; set; }
public virtual string RoleName { get; set; }
public virtual IList<UserModel> UsersInRole { get; set; }
public RoleModel()
{
UsersInRole = new List<UserModel>();
}
}
</code></pre>
<p>UserModelMap.cs:</p>
<pre><code>public class UserModelMap : ClassMap<UserModel>
{
public UserModelMap()
{
Table("Users");
Id(x => x.Id);
Map(x => x.RegisterDate);
Map(x => x.RegisterIp);
Map(x => x.EMail);
Map(x => x.Password);
Map(x => x.UserName);
Map(x => x.FirstName);
Map(x => x.LastName);
Map(x => x.WebSiteLink);
Map(x => x.FaceBookLink);
Map(x => x.TwitterLink);
Map(x => x.GooglePlusLink);
Map(x => x.PinterestLink);
Map(x => x.LastLogIn);
Map(x => x.LastLoginIP);
Map(x => x.About);
Map(x => x.IsActive);
Map(x => x.IsFreelancer);
Map(x => x.IsBanned);
HasManyToMany(x => x.UserRole).Table("UsersRoles")
.ParentKeyColumn("RoleId")
.ChildKeyColumn("UserId")
.LazyLoad()
.Cascade.All();
}
}
</code></pre>
<p>RoleModelMap.cs:</p>
<pre><code>public class RoleModelMap : ClassMap<RoleModel>
{
public RoleModelMap()
{
Table("Roles");
Id(x => x.Id);
Map(x => x.RoleName);
HasManyToMany(x => x.UsersInRole).Table("UsersRoles")
.ParentKeyColumn("RoleId")
.ChildKeyColumn("UserId")
.LazyLoad()
.Inverse();
}
}
</code></pre>
<p>In UserApiController.cs:</p>
<pre><code>[Route("User/Register")]
[HttpPost]
public string RegisterUser(object regUser)
{
RoleModel userRole = BlogModule.getUserRole();//Getting "User" role
UserModel newUser = JsonConvert.DeserializeObject<UserModel>(regUser.ToString());
string hashedPassword = BlogModule.PasswordToMD5(newUser.Password);
newUser.Password = hashedPassword;
newUser.RegisterDate = DateTime.Now;
newUser.UserRole.Add(userRole);
newUser.LastLogIn = DateTime.Now;
newUser.LastLoginIP = newUser.RegisterIp;
DbOperations.AddNewUserToDatabase(newUser);
string sonuc = "true";
return sonuc;
}
</code></pre>
<p>AddNewUserToDatabase(UserModel newUser):</p>
<pre><code>public static void AddNewUserToDatabase(UserModel newUser)
{
using (var session = NHibernateHelper.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
UserModel currentUser = session.QueryOver<UserModel>()
.Where(x => x.UserName == newUser.UserName)
.SingleOrDefault();
if (currentUser == null)
{
session.Save(newUser);
transaction.Commit();
}
}
}
}
</code></pre>
| 3 | 2,076 |
Adding zoom in/out and crop for photo
|
<p>I am trying to add capability to zoom in/out and crop a profile image before saving change but I am not sure how to go about this. Here below are my relevant codes:</p>
<pre><code>- (void)viewDidLoad {
...
NSString *urlString = [User sharedUser].avatar;
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[_avatarImageView setImageWithURLRequest:imageRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
_avatarImageView.image = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error: %@", error);
}];
_avatarImageView.layer.masksToBounds = YES;
_avatarImageView.layer.cornerRadius = _avatarImageView.frame.size.width / 2; //create circle image
[self initImagePicker];
...
}
- (void) initImagePicker {
myPicker = [[MyImagePicker alloc] init];
myPicker.SourceVC = self;
myPicker.SourceView = self.view;
myPicker.delegate = self;
myPicker.isImage = YES;
[myPicker initImagePicker];
}
- (IBAction) ChooseImageSourceAlbum {
tempType = POPUP_TYPE_IMAGPICKER;
selectArray = @[@"Camera",@"Choose Photos",@"Delete Photo"];
//Call popup
PopupTemplateViewController *vc = [[PopupTemplateViewController alloc] initWithNibName:@"PopupTemplateViewController" bundle:nil];
vc.delegate = self;
vc.dataArray = selectArray;
vc.type = POPUP_TYPE_OTHERS;
self.useBlurForPopup = NO;
[self presentPopupViewController:vc animated:YES completion:nil];
}
- (void) MyImagePickerTakePicture:(NSDictionary *)_dic {
NSString *mediaType = [_dic objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:@"public.image"]) {
UIImage *image = [_dic objectForKey:UIImagePickerControllerOriginalImage];
//??? add crop and zoom image here!!!
[self performSelector:@selector(processImage:) withObject:image afterDelay:0.25f];
}
}
- ( void )processImage:( UIImage * )image {
CGFloat ratio = 1.0;
if (image.size.width > 400) {
ratio = 400 / image.size.width;
}
else if (image.size.height > 600) {
ratio = 600 / image.size.height;
}
UIImage *imageResize = [self scaleImage:image toScale:ratio];
[_avatarImageView setImage:imageResize];
[self UpdateAvatar];
}
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize{
UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
[image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
- (void) UpdateAvatar {
[self showSeachingPopViewinView:self.view type:POPUP_TYPE_UPDATE];
NSString *account = [[User sharedUser] account];
NSMutableDictionary *parameters = [NSMutableDictionary new];
[parameters setObject:account forKey:@"account"];
[parameters setObject:_avatarImageView.image forKey:@"avatar"];
[GatewayManager callUpdateAvatar:parameters delegate:self];
}
- (void)popupView:(PopupTemplateViewController *)popupView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self dismissPopupViewControllerAnimated:NO completion:nil];
NSString *str = selectArray[indexPath.row];
if ([str isEqualToString:@"Camera"]) {
[myPicker OpenCamera];
}
else if ([str isEqualToString:@"Choose Photos"]) {
[myPicker OpenAlbum];
} else {
[self deletePhoto];
}
}
</code></pre>
<p>Now when I tab the profile image it will pop up view showing 3 choices: Camera, Choose Photo, Delete Photo. What I want to achieve is that after taking a photo or choosing a photo I want to have another view with the photo that I can zoom in/out and crop. Thanks in advance.</p>
| 3 | 1,451 |
Android Activity to test Backlight
|
<p>I am trying to make a simple blank app that tests the backlight of the phone. The activity works, it turns the brightness up to 255. However the app never shuts down, when I add onDestroy() at the end it crashes. It also throws exceptions anywhere the Settings.System... is called but does not crash. I would also like to be able to reset it to default brightness after the apps runs. I have been playing with this simple app for so long and cant get it right, please help!!! </p>
<pre><code>public class BacklightActivity extends Activity {
int brightness = 255;
public final static String log_tag = "Backlight";
private Handler mHandler = new Handler();
int delay = 10000;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(log_tag,"Entered onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_backlight);
/*
* API's to launch the application when the tablet is locked or
* display is turned off
*/
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
createTempFile("Status_Backlight.txt", "INPROGRESS");
try {
//this will set the manual mode (set the automatic mode off)
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
//Sets the bightness of the backlight (1-255) britness is set at max of 255
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness); //this will set the brightness to maximum (255)
//refreshes the screen
int br = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = (float) br / 255;
getWindow().setAttributes(lp);
} catch (Exception e) {
}
//Delay turing off flash and then end activity
mHandler.postDelayed(new Runnable() {
public void run() {
Log.i(log_tag,"Entered sleep");
}
}, delay);
// Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
}
private void exit_function(){
onDestroy();
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(log_tag,"Entered onDestroy()");
createTempFile("Status_Backlight.txt", "COMPLETED");
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
finish();
}
</code></pre>
| 3 | 1,153 |
CView as tab on CMFCTabCtrl, does not draw invalidated area (on dragging)
|
<p>I have a <code>CWinAppEx</code> MDI application, VS2017. The <code>ChiledFrame</code> is covered with (I altered the names for this question) <code>CMyView</code>:</p>
<pre><code>pDocTemplate = new CMultiDocTemplate( IDR_MYTYPE,
RUNTIME_CLASS(CMyDoc),
RUNTIME_CLASS(CMyChildFrame),
RUNTIME_CLASS(CMyView));
</code></pre>
<p><code>CMyView</code> client-rect is covered with a <code>CMFCTabCtrl</code> (<code>m_wndTabs</code>): It has 2 tabs, objects of <code>CViewTest1</code> and <code>CViewTest2</code> classes (derived from MFC <code>CView</code>). This is the relevant part of <code>MyView::Create</code> function:</p>
<pre><code> CRect rectDummy;
rectDummy.SetRectEmpty();
// Create tabs window:
if (!m_wndTabs.Create(CMFCTabCtrl::STYLE_3D_ONENOTE, rectDummy, this, 1))
{
TRACE0("Failed to create output tab window\n");
return -1; // fail to create
}
// Create output panes ('300' value is dummy client-rect is updated on CViewTest1/2::OnSize):
CViewTest1 *pWnd1 = (CViewTest1*)RUNTIME_CLASS(CViewTest1)->CreateObject();
pWnd1->Create(nullptr, nullptr, LBS_NOINTEGRALHEIGHT | WS_CHILD | WS_VISIBLE, CRect(0, 0, 300, 300), this, 1, pContext);
pWnd1->SetFont(&afxGlobalData.fontRegular);
CViewTest2 *pWnd2 = (CViewTest2*)RUNTIME_CLASS(CViewTest2)->CreateObject();
pWnd2->Create(nullptr, nullptr, LBS_NOINTEGRALHEIGHT | WS_CHILD | WS_VISIBLE, CRect(0, 0, 300, 300), this, 2, pContext);
pWnd2->SetFont(&afxGlobalData.fontRegular);
m_wndTabs.AddTab(pWnd1, L"Tab 1");
m_wndTabs.AddTab(pWnd2, L"Tab 2");
// Redraw tab 0 ("Tab 1"): <--- Here already smells an issue.
m_wndTabs.SetActiveTab(1); // (This need to move to 1 & back to 0)
m_wndTabs.SetActiveTab(0);
</code></pre>
<p>The <code>parent</code> of <code>CViewTest1</code> and <code>CViewTest2</code> objects is <code>CMyView</code> object.
m_wndTabs resized to cover the whole client area at:</p>
<pre><code>void CMyView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
if (m_wndTabs) // Tab control should cover the whole client area:
m_wndTabs.SetWindowPos(nullptr, -1, -1, cx, cy, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
}
</code></pre>
<p>Now, when I drag one child-frame over another, and back: The control-tab behaves as expected, but CViewTest1 object (on active tab) does not get OnDraw(). It looks like that:</p>
<p><a href="https://i.stack.imgur.com/eNdF4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eNdF4.jpg" alt="enter image description here"></a></p>
<p><strong>Any idea?</strong></p>
| 3 | 1,230 |
AngularJs nexted view
|
<p>Hi I am going to start a project.
In tablet page contains list of items on left side and item detail on right side as shown in below image.<img src="https://i.stack.imgur.com/Mjcma.png" alt="enter image description here"></p>
<p>In mobile It shows list of items on one page and detail of activity on another page, like below images.<img src="https://i.stack.imgur.com/YkqWW.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/oNzkU.png" alt="enter image description here"></p>
<p>I have used AngularJs to implemented this application like this(pseudo code)</p>
<h2>Index.html</h2>
<pre><code><html>
<head></head>
<boby>
<ui-view></ui-view>
</body>
</html>
</code></pre>
<hr>
<h2>List.html</h2>
<pre><code><ul><li ng-repeat='item in items' >{{item.title}}</li></ul>
<div id="middleContent" ui-view style="padding-left: 320px;"></div>
</code></pre>
<hr>
<h2>detail.html</h2>
<pre><code><div>Acitivity detail <div>
</code></pre>
<h2>config.js</h2>
<pre><code>app = angular.module('MyApp', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider.state('List', {
url: '/List',
templateUrl: 'Partial/List.html',
controller: 'ListController'
})
$stateProvider.state('Detail', {
url: '/Detail/:id',
templateUrl: 'Partial/Detail.html',
controller: 'DetailController'
})
$stateProvider.state('TabletList', {
url: '/TabletList',
data: { 'parent': 'tablet' },
templateUrl: 'Partial/List.html',
controller: 'ListController'
})
$stateProvider.state('TabletList.Detail', {
url: '/Detail/:id',
templateUrl: 'Partial/Detail.html',
controller: 'DetailController',
})
})
</code></pre>
<hr>
<h2>In Controller.js</h2>
<pre><code>app.controller('ListController',function(){
if($(window).width() > mobileView )( $state.go('TabletList.Detail'))
})
</code></pre>
<hr>
<p>In List.html I have use next view</p>
<pre><code><div id="middleContent" ui-view style="padding-left: 317px;"></div>
</code></pre>
<p>It get loaded in case of tablet . otherwise it is useless there.</p>
<p>Is there some simple way to handle this scenario. please help</p>
<p>with regards</p>
| 3 | 1,082 |
How to send tile and toast push notification at a time in windows phone using php code?
|
<p>I am developing for Windows Phone 8. I need to send toast and tile push notification at a time using PHP. I can receive toast or tile notification successfully but I need to combine these notifications. Can anyone tell me how to solve this issue?</p>
<p>My code is given below</p>
<pre><code><?php
class WindowsPhonePushPriority
{
const TileImmediately = 1;
}
class WindowsPhonePushClient
{
private $device_url = '';
private $debug_mode = false;
function __construct($device_url)
{
$image_url = 'Images/purple.jpg';
$this->device_url = $device_url;
}
public function send_tile_update($message1, $title, $priority = WindowsPhonePushPriority::TileImmediately)
{
$title = 'push from Bestin Uk';
$msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>".
"<wp:Notification xmlns:wp=\"WPNotification\">".
"<wp:Tile>".
"<wp:BackgroundImage>".$imageURL."</wp:BackgroundImage>".
"<wp:Count>".$message1."</wp:Count>".
"<wp:Title>".$title."</wp:Title>".
"<wp:Param>/Receive.xaml?NavigatedFrom=push</wp:Param>".
"</wp:Tile>".
"</wp:Notification>";
return $this->_send_push(array('X-WindowsPhone-Target: token','X-NotificationClass: ' . $priority,), $msg);
}
private function _send_push($headers, $msg)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->device_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, // Add these headers to all requests
$headers + array(
'Content-Type: text/xml',
'Accept: application/*'
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
if ($this->debug_mode)
{
curl_setopt($ch, CURLOPT_VERBOSE, $this->debug_mode);
curl_setopt($ch, CURLOPT_STDERR, fopen('debug.log','w'));
}
$output = curl_exec($ch);
echo $output;
curl_close($ch);
return array(
'X-SubscriptionStatus' => $this->_get_header_value($output, 'X-SubscriptionStatus'),
'X-NotificationStatus' => $this->_get_header_value($output, 'X-NotificationStatus'),
'X-DeviceConnectionStatus' => $this->_get_header_value($output, 'X-DeviceConnectionStatus')
);
}
private function _get_header_value($content, $header)
{
return preg_match_all("/$header: (.*)/i", $content, $match) ? $match[1][0] : "";
}
}
?>
</code></pre>
<p>I have tried combined code but I am getting some time xml payload error</p>
| 3 | 1,259 |
getting value from a list
|
<p>I have a xml that looks like this:</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" version="1.0" xml:lang="en">
<title type="text">Google Hot Trends</title>
<subtitle type="text">What are people searching for on Google today?</subtitle>
<id>http://www.google.com/trends/hottrends/atom/hourly,2007-08</id>
<link href="http://www.google.com/trends/hottrends/atom/hourly" rel="self"/>
<updated>2010-12-01T14:03:30Z</updated>
<entry xmlns="http://www.w3.org/2005/Atom">
<id>2010-12-01T14:03:30Z</id>
<title type="text"><![CDATA[rosa parks, adam levine girlfriend, meet the famous, ...]]></title>
<content type="html"><![CDATA[<ol>
<li><span class="Mild up2"><a href="http://www.google.com/trends/hottrends?q=rosa+parks&date=2010-12-1&sa=X">rosa parks</a></span></li>
<li><span class="Mild down1"><a href="http://www.google.com/trends/hottrends?q=adam+levine+girlfriend&date=2010-12-1&sa=X">adam levine girlfriend</a></span></li>
<li><span class="Mild down1"><a href="http://www.google.com/trends/hottrends?q=meet+the+famous&date=2010-12-1&sa=X">meet the famous</a></span></li>
<li><span class="Mild equal"><a href="http://www.google.com/trends/hottrends?q=sons+of+anarchy+season+4&date=2010-12-1&sa=X">sons of anarchy season 4</a></span></li>
<li><span class="Mild equal"><a href="http://www.google.com/trends/hottrends?q=victoria+secret+angels&date=2010-12-1&sa=X">victoria secret angels</a></span></li>
<li><span class="Mild up5"><a href="http://www.google.com/trends/hottrends?q=happy+hanukkah&date=2010-12-1&sa=X">happy hanukkah</a></span></li>
<li><span class="Mild down1"><a href="http://www.google.com/trends/hottrends?q=katy+perry+victoria+secret+fashion+show&date=2010-12-1&sa=X">katy perry victoria secret fashion show</a></span></li>
<li><span class="Mild down1"><a href="http://www.google.com/trends/hottrends?q=married+to+the+mob+clothing&date=2010-12-1&sa=X">married to the mob clothing</a></span></li>
<li><span class="Mild down1"><a href="http://www.google.com/trends/hottrends?q=victoria+secret+models+names+and+pictures&date=2010-12-1&sa=X">victoria secret models names and pictures</a></span></li>
<li><span class="Mild equal"><a href="http://www.google.com/trends/hottrends?q=world+aids+day+2010&date=2010-12-1&sa=X">world aids day 2010</a></span></li>
<li><span class="Mild up6"><a href="http://www.google.com/trends/hottrends?q=shahla+jahed&date=2010-12-1&sa=X">shahla jahed</a></span></li>
<li><span class="Mild equal"><a href="http://www.google.com/trends/hottrends?q=interpol&date=2010-12-1&sa=X">interpol</a></span></li>
<li><span class="Mild up18"><a href="http://www.google.com/trends/hottrends?q=wallis+simpson&date=2010-12-1&sa=X">wallis simpson</a></span></li>
<li><span class="Mild up46"><a href="http://www.google.com/trends/hottrends?q=chanukah&date=2010-12-1&sa=X">chanukah</a></span></li>
<li><span class="Mild new"><a href="http://www.google.com/trends/hottrends?q=hiv+symptoms&date=2010-12-1&sa=X">hiv symptoms</a></span></li>
<li><span class="Mild up6"><a href="http://www.google.com/trends/hottrends?q=santa+tracker&date=2010-12-1&sa=X">santa tracker</a></span></li>
<li><span class="Mild down8"><a href="http://www.google.com/trends/hottrends?q=vs+fashion+show+2010&date=2010-12-1&sa=X">vs fashion show 2010</a></span></li>
<li><span class="Mild down3"><a href="http://www.google.com/trends/hottrends?q=advent+calendar&date=2010-12-1&sa=X">advent calendar</a></span></li>
<li><span class="Mild up8"><a href="http://www.google.com/trends/hottrends?q=december+1&date=2010-12-1&sa=X">december 1</a></span></li>
<li><span class="Mild up19"><a href="http://www.google.com/trends/hottrends?q=aids+ribbon&date=2010-12-1&sa=X">aids ribbon</a></span></li>
</ol>
]]></content></entry></feed>
</code></pre>
<p>How would i be able to get the values from the <code><a></code> tags that are inside the <code><li></code> tags?</p>
| 3 | 2,504 |
HOW TO FIX Mongoose 5.11.8 model.find() ERROR Operation `thanks-leaderboards.find()` buffering timed out after 10000ms
|
<p>How to solve model.find() function produces "buffering timed out after ... ms"? I'm using mongoose v 5.11.8, npm v6.14.8 and mongodb v3.6.3</p>
<p>Here's the code.</p>
<p>thanks-leaderboard.js</p>
<pre><code>const thanksLeaderboardSchema = require('../../schemas/thanks-leaderboard-schema.js')
const thanksSchema = require('../../schemas/thanks-schema.js')
const fetchTopMembers = async (guildId) => {
let text = ''
const results = await thanksSchema
.find({
guildId,
})
.sort({
received: -1,
})
.limit(10)
for (let counter = 0; counter < results.length; ++counter) {
const { userId, received = 0 } = results[counter]
text += `#${counter + 1} <@${userId}> with ${received} thanks\n`
}
text += '\nThis is updated every minute'
return text
}
const updateLeaderboard = async (client) => {
const results = await thanksLeaderboardSchema.find({}).where('channelId')
for (const result of results) {
const { channelId, _id: guildId } = result
const guild = client.guilds.cache.get(guildId)
if (guild) {
const channel = guild.channels.cache.get(channelId)
if (channel) {
const messages = await channel.messages.fetch()
const firstMessage = messages.first()
const topMembers = await fetchTopMembers(guildId)
if (firstMessage) {
firstMessage.edit(topMembers)
} else {
channel.send(topMembers)
}
}
}
}
setTimeout(() => {
updateLeaderboard(client)
}, 1000 * 60)
}
module.exports = async (client) => {
updateLeaderboard(client)
}
</code></pre>
<p>set-leaderboard.js</p>
<pre><code>const leaderBoardSchema = require('../../schemas/thanks-leaderboard-schema.js')
module.exports = {
commands: 'setleaderboard',
requiredRoles: ['Administrator'],
description: 'Erstelle ein Leaderboard für die vergebenen Danksagungen',
callback: async (message) => {
const { guild, channel} = message
const guildId = guild.id
const channelId = channel.id
await leaderBoardSchema.findOneAndUpdate({
_id: guildId,
channelId,
},
{
_id: guildId,
channelId,
},
{
upsert: true,
})
message.reply('Leaderboard wurde erstellt!').then((message) => {
message.delete({
timeout: 1000 * 5,
})
})
message.delete()
}
}
</code></pre>
<p>thanks-leaderboard-schema.js</p>
<pre><code>const mongoose = require('mongoose')
const reqString = {
type: String,
required: true,
}
const thanksLeaderboardSchema = mongoose.Schema({
// Guild ID
_id: reqString,
channelId: reqString,
})
module.exports = mongoose.model('thanks-leaderboards', thanksLeaderboardSchema, 'thanks-leaderboards')
</code></pre>
<p>thanks-schema.js</p>
<pre><code>const mongoose = require('mongoose')
const reqString = {
type: String,
required: true,
}
const thanksSchema = mongoose.Schema({
userId: reqString,
guildId: reqString,
received: {
type: Number,
default: 0,
},
lastGave: Date,
})
module.exports = mongoose.model(
'thanks',
thanksSchema,
'thanks'
)
</code></pre>
<p>I tried increasing the bufferTimeoutMS or disabling the bufferCommands but still it won't work. This Code is supposed to readout the database every 60 seconds but the timeout happens after 10 seconds... can't figure out how to fix this error. I've already tried to delete the node_modules folders for mongoose and mongodb and reinstall them via npm but that didn't work as I get this error again.</p>
| 3 | 1,510 |
Conditional [required] attribute in Angular 9 form - ExpressionChangedAfterItHasBeenCheckedError
|
<p>I have a radio button like so:</p>
<pre><code><div class="col-sm-6 col-md-4">
<div class="form-group" [ngClass]="{ 'is-invalid': saCitizen.invalid }">
<label for="saCitizen">
Do you have South African citizenship?:
</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="saCitizen" id="saCitizen_yes" [value]="true" [(ngModel)]="registration.saCitizen" required #saCitizen="ngModel">
<label class="form-check-label" for="saCitizen_yes">Yes</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="saCitizen" id="saCitizen_no" [value]="false" [(ngModel)]="registration.saCitizen" required>
<label class="form-check-label" for="saCitizen_no">No</label>
</div>
</div>
<div *ngIf="saCitizen.errors?.required" class="invalid-feedback">
SA Citizen is required
</div>
</div>
</div>
</code></pre>
<p>I then have a texbox asking for the ID number:</p>
<pre><code><div class="col-sm-6 col-md-4">
<div class="form-group" [ngClass]="{ 'is-invalid': idNumber.invalid }">
<label for="idNumber">
RSA ID Number:
</label>
<input id="idNumber" name="idNumber" class="form-control" type="text" [(ngModel)]="registration.idNumber" #idNumber="ngModel" maxlength="13" minlength="13" pattern="^\d{13}$" [required]="registration.saCitizen" />
<div *ngIf="idNumber.errors?.required" class="invalid-feedback">
RSA ID Number is required
</div>
</div>
</div>
</code></pre>
<p>The key part is: <code>[required]="registration.saCitizen"</code> on the textbox. This gives rise to the following error when I change the radio button:</p>
<pre><code>ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.
</code></pre>
<p>How do I avoid this error but keep the conditional validation / required aspect?</p>
| 3 | 1,363 |
issues with setting up javafx package controllers
|
<p>I am trying to organize my project , but when I try to load my controller , and I got <code>java.lang.reflect.InvocationTargetException</code> but I have the right path. how can I fix this?</p>
<pre><code><AnchorPane id="AnchorPane" prefHeight="570.0" prefWidth="784.0" styleClass="root" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="user.ui.main.StrixController">
</code></pre>
<p>error </p>
<pre><code>file:/home/xxxx/NetBeansProjects/strixx/dist/run385118534/xxxx.jar!/user/ui/main/strix.fxml:10
</code></pre>
<p>treeview </p>
<pre><code>├── resources
│ ├── images
│ │ ├── 156081805144861603.png
│ │ └── icon
│ │ ├── blueGlass.png
│ │ ├── exploit.png
│ │ ├── icon.png
│ │ └── shaker.png
│ └── theme
│ └── dark.theme.css
├── strix
│ └── ui
│ ├── about
│ │ ├── aboutController.java
│ │ └── about.fxml
│ └── main
│ ├── StrixController.java
│ ├── strix.fxml
│ └── Strix.java
└── util
└── strixUtil.java
</code></pre>
<pre><code>Executing /home/blackleitus/NetBeansProjects/JavaFXApplication11/dist/run981614013/JavaFXApplication11.jar using platform /usr/lib/jvm/java-8-oracle/jre/bin/java
Gtk-Message: 00:24:34.842: Failed to load module "pantheon-filechooser-module"
(java:17030): Gtk-WARNING **: 00:24:34.848: Unable to locate theme engine in module_path: "pixmap",
(java:17030): Gtk-WARNING **: 00:24:34.848: Unable to locate theme engine in module_path: "pixmap",
(java:17030): Gtk-WARNING **: 00:24:34.848: Unable to locate theme engine in module_path: "pixmap",
(java:17030): Gtk-WARNING **: 00:24:34.848: Unable to locate theme engine in module_path: "pixmap",
Gtk-Message: 00:24:34.849: Failed to load module "canberra-gtk-module"
Exception in Application start method
java.lang.reflect.InvocationTargetException
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 com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
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 sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$412(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: javafx.fxml.LoadException: Error resolving onAction='#handleAboutAction', either the event handler is not in the Namespace or there is an error in the script.
file:/home/blackleitus/NetBeansProjects/JavaFXApplication11/dist/run981614013/JavaFXApplication11.jar!/javafxapplication11/ui/main/FXMLDocument.fxml:26
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2597)
at javafx.fxml.FXMLLoader.access$100(FXMLLoader.java:103)
at javafx.fxml.FXMLLoader$Element.processEventHandlerAttributes(FXMLLoader.java:610)
at javafx.fxml.FXMLLoader$ValueElement.processEndElement(FXMLLoader.java:770)
at javafx.fxml.FXMLLoader.processEndElement(FXMLLoader.java:2823)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2532)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at javafxapplication11.ui.main.JavaFXApplication11.start(JavaFXApplication11.java:22)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$419(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$399(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$397(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$398(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$203(GtkApplication.java:139)
... 1 more
Exception running application javafxapplication11.ui.main.JavaFXApplication11
Java Result: 1
</code></pre>
| 3 | 2,060 |
one to many relationship in app engine is not working properly when used in android client
|
<p>I am trying to use one to many and many to one relationship in modelling the relationship of student and teacher. When I try to persist teacher with students in android app, teacher and students are persisted but I get the following error. And then when I try to list all students I get the same error.
Error log on android side:</p>
<pre><code>06-17 10:10:43.394: W/System.err(27823): com.google.api.client.googleapis.json.GoogleJsonResponseException: 503 Service Unavailable
06-17 10:10:43.399: W/System.err(27823): {
06-17 10:10:43.399: W/System.err(27823): "code" : 503,
06-17 10:10:43.399: W/System.err(27823): "errors" : [ {
06-17 10:10:43.399: W/System.err(27823): "domain" : "global",
06-17 10:10:43.399: W/System.err(27823): "message" : "",
06-17 10:10:43.399: W/System.err(27823): "reason" : "backendError"
06-17 10:10:43.399: W/System.err(27823): } ],
06-17 10:10:43.399: W/System.err(27823): "message" : ""
06-17 10:10:43.399: W/System.err(27823): }
06-17 10:10:43.399: W/System.err(27823): at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
06-17 10:10:43.399: W/System.err(27823): at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
06-17 10:10:43.399: W/System.err(27823): at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:312)
06-17 10:10:43.404: W/System.err(27823): at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1045)
06-17 10:10:43.404: W/System.err(27823): at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
06-17 10:10:43.404: W/System.err(27823): at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
06-17 10:10:43.404: W/System.err(27823): at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
06-17 10:10:43.404: W/System.err(27823): at com.schoolhydra.MainActivity$SendInfo.doInBackground(MainActivity.java:96)
06-17 10:10:43.404: W/System.err(27823): at com.schoolhydra.MainActivity$SendInfo.doInBackground(MainActivity.java:1)
06-17 10:10:43.404: W/System.err(27823): at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-17 10:10:43.404: W/System.err(27823): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
06-17 10:10:43.404: W/System.err(27823): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
06-17 10:10:43.404: W/System.err(27823): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
06-17 10:10:43.404: W/System.err(27823): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
06-17 10:10:43.404: W/System.err(27823): at java.lang.Thread.run(Thread.java:841)
</code></pre>
<p>Error log on server side:</p>
<pre><code>Uncaught exception from servlet
java.io.IOException: com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: Unable to get a resource (through reference chain: com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->com.schoolhydra.Teacher["students"]->java.util.ArrayList[0]->com.schoolhydra.Student["teacher"]->c...(length 618733)
</code></pre>
<p>and warning, which came up with error:</p>
<pre><code>com.google.appengine.datanucleus.MetaDataValidator warn: Meta-data warning for com.schoolhydra.Student.teacher: Error in meta-data for com.schoolhydra.Student.teacher : The datastore does not support joins and therefore cannot honor requests to place related objects in the default fetch group. The field will be fetched lazily on first access. You can modify this warning by setting the datanucleus.appengine.ignorableMetaDataBehavior property in your config. A value of NONE will silence the warning. A value of ERROR will turn the warning into an exception.
</code></pre>
<p>Teacher class</p>
<pre><code>@Entity
public class Teacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key id;
private String name;
private String surname;
@OneToMany(mappedBy = "teacher", cascade = CascadeType.ALL)
private List<Student> students = new ArrayList<Student>();
public Key getId() {
return id;
}
public void setId(Key id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
</code></pre>
<p>Student class</p>
<pre><code>@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key id;
private String name;
private String surname;
@ManyToOne
private Teacher teacher;
public Key getId() {
return id;
}
public void setId(Key id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
</code></pre>
<p>it seems that problem arises when I use mappedBy in @OneToMany. I am using datastore as databse. Is there some restriction, that datastore does not support mappedBy, because it is not relational database?</p>
<p>Can anyone help me with this problem?</p>
| 3 | 5,772 |
non-broadcastable output operand with shape (30,1) doesn't match the broadcast shape (30,30)
|
<p>implement a new function to calculate the new objective function and gradients</p>
<p>Got following error
for the Stochastic Gradient descent.
I don't know what seems to be the problem
as my matrix is already 30 by 1</p>
<pre><code>def stochastic_objective_gradient(w, xi, yi, lam):
d = xi.shape[0]
yx = yi * xi # 1-by-d matrix
yxw = float(numpy.dot(yx, w)) # scalar
# calculate objective function Q_i
loss = numpy.log(1 + numpy.exp(-yxw)) # scalar
reg = lam / 2 * numpy.sum(w * w) # scalar
obj = loss + reg
# calculate stochastic gradient
g_loss = -yx.T / (1 + numpy.exp(yxw)) # d-by-1 matrix
g = g_loss + lam * w # d-by-1 matrix
return obj, g
def sgd(x, y, lam, stepsize, max_epoch=100, w=None):
n, d = x.shape
objvals = numpy.zeros(max_epoch) # store the objective values
if w is None:
w = numpy.zeros((d, 1)) # zero initialization
for t in range(max_epoch):
# randomly shuffle the samples
rand_indices = numpy.random.permutation(n)
x_rand = x[rand_indices, :]
y_rand = y[rand_indices, :]
objval = 0 # accumulate the objective values
for i in range(n):
xi = x_rand[i, :] # 1-by-d matrix
yi = float(y_rand[i, :]) # scalar
obj, g = stochastic_objective_gradient(w, xi, yi, lam)
objval += obj
w -= stepsize * g
stepsize *= 0.9 # decrease step size
objval /= n
objvals[t] = objval
print('Objective value at epoch t=' + str(t) + ' is ' + str(objval))
return w, objvals
</code></pre>
<p>What can be done to match the shape?</p>
<pre><code> ```
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-195-06f44b846812> in <module>()
3 lam = 0
4 stepsize = 0.1
----> 5 w, objvals_sgd = sgd(x_train, y_train, lam, stepsize)
<ipython-input-79-54d9a7949c9d> in sgd(x, y, lam, stepsize, max_epoch, w)
33 obj, g = stochastic_objective_gradient(w, xi, yi, lam)
34 objval += obj
---> 35 w -= stepsize * g
36
37 stepsize *= 0.9 # decrease step size
ValueError: non-broadcastable output operand with shape (30,1) doesn't match the broadcast shape (30,30)
```
</code></pre>
| 3 | 1,197 |
How can I show my modal outside my sidenav? I'm using :host. Angular
|
<p>I have a :host with hostlistener() in my navmenu-component.ts. I made this so I can have a sidemenu which slides out of my sidenavbar when i press a button.</p>
<p>I want to call a modal to edit something. So I have made a modal in the navmenu-component.html. Whenever I call my modal it shows in the collapsable menu.</p>
<p>I don't know how I can make this show outside my collapsable menu, I think it has something to do with my :host but i can't seem to find out what to do.</p>
<p>here are my components</p>
<p>this is my navmenu-component.html</p>
<pre><code> <div class="environmentHolder w100" (click)="openClose()">
<div class="dropdown-env" >
<div class="header">
<p>{{textDDL}}<fa-icon [icon]="arrow"></fa-icon></p>
</div>
</div>
<div *ngIf="environments.length == 0; else divFilled">
<div class="dropdown-env-content slidedown" #ddl >
<p (click)='goToEnv()'>Create New Environment <fa-icon [icon]="plus"></fa-icon></p>
<h6>0/2</h6>
</div>
</div>
<ng-template #divFilled>
<div class="dropdown-env-content slidedown1env" #ddl *ngFor="let item of environments">
<input type="image" id="dropbtn" src="assets/menu.png" style="width: 30px; height: 20px; border: none; transform: rotate(90deg);" aria-controls="drop1" class="button dropdown" (click)="openMenu()"/><br>
<ul id="drop1" data-dropdown-content class="f-dropdown" style="display: none; margin-right: 15px;">
<li><a (click)="goToEnvUpdate(item.id)" #editButton >Edit</a></li>
<li><a #deleteButton >Delete</a></li>
</ul>
<p [ngClass]="isVisible" *ngFor="let env of environments" (click)="getEnvironment(env.id)" >{{env.name}}</p>
<div *ngIf="environments.length &lt; 2">
<p (click)='goToEnv()' [ngClass]="isVisible">Create New Environment <fa-icon [icon]="plus"></fa-icon></p>
</div>
<div *ngIf="environments.length == 1"><h6 [ngClass]="isVisible">1/2</h6></div>
<div *ngIf="environments.length == 2"><h6 [ngClass]="isVisible">2/2</h6></div>
</div>
</ng-template>
<div class="foldable-title">
<p>Application</p>
</div>
<div class="foldable-content">
<div (click)="toggleMenu()">
<a class="foldable-text" href="">Overview</a><br>
</div>
<a class="foldable-text" href="">Create new</a><br>
<a class="foldable-text" href="">Open</a>
</div>
<div class="foldable-title">
<p>Business Process</p>
</div>
<div class="foldable-content">
<a class="foldable-text" href="">Overview</a><br>
<a class="foldable-text" href="">Create new</a><br>
<a class="foldable-text" href="">Open</a>
</div>
<div class="foldable-title">
<p>Capability</p>
</div>
<div class="foldable-content">
<a class="foldable-text" href="">Overview</a><br>
<a class="foldable-text" href="">Create new</a><br>
<a class="foldable-text" href="">Open</a>
</div>
<div class="foldable-title">
<p>Program & Project</p>
</div>
<div class="foldable-content">
<a class="foldable-text" href="">Overview</a><br>
<a class="foldable-text" href="">Create new</a><br>
<a class="foldable-text" href="">Open</a>
</div>
<div class="foldable-title">
<p>Resource</p>
</div>
<div class="foldable-content">
<a class="foldable-text" href="">Overview</a><br>
<a class="foldable-text" href="">Create new</a><br>
<a class="foldable-text" href="">Open</a>
</div>
<div class="foldable-title">
<p>Strategy</p>
</div>
<div class="foldable-content">
<a class="foldable-text" href="">Overview</a><br>
<a class="foldable-text" href="">Create new</a><br>
<a class="foldable-text" href="">Open</a>
</div>
<div class="foldable-title">
<p>SWOT-analysis</p>
</div>
<div class="foldable-content">
<a class="foldable-text" href="">Overview</a><br>
<a class="foldable-text" href="">Create new</a><br>
<a class="foldable-text" href="">Open</a>
</div>
<br>
<app-collapse [@slideInOut]="menuState" ></app-collapse>
</div>
<div class="outside-navMenu">
<div #editModal class="modal">
<div class="card w40">
<form [formGroup]="environmentForm" class="form" (ngSubmit)="onSubmit()">
<div class="card-title">
<p>Update your environment</p>
</div>
<div class="card-body">
<br />
<div class="card-input">
<input formControlName="name" type="text" class="input w70" placeholder="Name" />
</div>
<br />
<br />
<button class="btn btn-primary-create" type="submit">save</button><br /><br />
</div>
</form>
<div class="bar"></div>
</div>
</div>
</div>
</code></pre>
<p>this is my navmenu-component.css</p>
<pre><code>:host {
margin-left: -400px; /* makes menu dissapear when collapsed */
padding-left: 140px;
color: #17313e;
background-color: white;
height:96.81%;
width: 380px;
position: fixed;
border-radius: 0 30px 30px 0;
box-shadow: 3px 3px 3px 1px rgba(0, 0, 0, 0.2);
z-index: 1000;
top: 0;
left: 0;
overflow-x: hidden;
padding-top: 20px;
transition: 0.5s;
bottom: 2em;
}
.foldable-title p {
padding-top: 1em;
font-style: normal;
font-size: 18pt;
transition: 0.3s;
}
.foldable-content {
padding-bottom: 1em;
padding-left: 2.5em;
border-left: 2px solid #a4a4a4;
height: 11.5%;
transition: 0.3s;
}
.foldable-text {
font-size: 14pt;
font-style: normal;
color: #787878;
text-decoration: none;
line-height: 2;
transition: 0.3s;
}
.foldable-text:hover{
color: #56a5da;
}
/* editbutton */
#dropbtn{
float: right;
width: 10px;
height: 10px;
margin: 0;
}
#deleteButton{
cursor: pointer;
}
#editButton{
cursor: pointer;
}
a{
color: #17313e;
text-decoration: none;
}
li {
list-style-type: none;
text-align: left;
}
ul {
padding: 2px;
padding-bottom: 4px;
margin-top: -10px;
}
ul :hover {
background-color: #f0f0f0;
}
#drop1{
display: none;
}
.f-dropdown {
z-index: 1000;
background-color: white;
width: 60px;
float: right;
border-radius: 5px;
box-shadow: 3px 3px 3px 1px rgba(0, 0, 0, 0.2);
}
/* dropdown */
.environmentHolder:hover{
cursor: pointer;
}
.environmentHolder{
position: relative;
}
.dropdown-env{
margin-top: 15px;
width: 220px;
height: 2em;
background-color: rgb(243, 241, 241);
margin-right: 20px;
border-radius: 5px;
color: #17313E;
}
.dropdown-env p{
padding-top: 1.3%;
padding-left: 5%;
position: relative;
}
.dropdown-env-content{
width: 220px;
color: #17313E;
background-color: rgb(243, 241, 241);
margin-right: 20px;
border-radius: 0 0 5px 5px;
margin-top: -4px;
position: absolute;
z-index: 3;
display: none;
height: auto;
box-shadow: 3px 3px 3px 1px rgba(0, 0, 0, 0.2);
}
.dropdown-env-content p:hover{
background-color: rgb(223, 223, 223);
}
.dropdown-env-content p:nth-child(1){
margin-top: 2%;
padding-left: 5%;
}
.dropdown-env-content p{
padding-top: 0;
margin-bottom: 2%;
padding-left: 5%;
}
fa-icon{
color:#17313E;
position: absolute;
right: 5%;
}
h6{
color:#17313E;
font-size: .7em;
text-align: right;
margin: 0;
padding-right: 4.6%;
padding-bottom: 3%;
font-weight: 400;
}
.slidedown{
animation-duration: 0.3s;
animation-name: lineInserted;
transition: height 0.3s;
}
.slidedown1env{
animation-duration: 0.3s;
animation-name: lineInserted1env;
transition: height 0.3s;
}
.d-none{
display: none;
}
.d-block{
display: block;
}
/* Modal */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 9999; /* Sit on top */
top: 0;
left: 0;
padding-left: 25%;
padding-top: 10em;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.outside-navmenu{
width: 100%;
height: 100%;
}
</code></pre>
<p>this is my navmenu-component.ts</p>
<pre><code>import { NumberSymbol } from '@angular/common';
import { Component, ElementRef, HostListener, Input, OnInit, Renderer2, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, NgModel, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { faChevronDown, faPlus } from '@fortawesome/free-solid-svg-icons';
import { Capability } from 'src/app/services/capability/Capability';
import { Environment } from 'src/app/services/environments/Environment';
import { EnvironmentsService } from 'src/app/services/environments/environments.service';
import { Strategy } from 'src/app/services/strategy/strategy';
@Component({
selector: 'app-nav-menu',
templateUrl: './nav-menu.component.html',
styleUrls: ['./nav-menu.component.css'],
animations: [
trigger('slideInOut', [
state('in', style({
transform: 'translate3d(0,0,0)'
})),
state('out', style({
transform: 'translate3d(100%, 0, 0)'
})),
transition('in => out', animate('300ms ease-in-out')),
transition('out => in', animate('300ms ease-in-out')),
])
]
})
/**
* @class
* this class will create sliding behaviour for the nav menu
*/
export class NavMenuComponent implements OnInit {
@ViewChild('editModal', { static: false }) editModal: any;
@ViewChild('ddl', { static: false }) ddl: any;
filterModel!: NgModel;
arrow = faChevronDown;
plus = faPlus;
textInvisible: boolean = true;
environment!: Environment;
newEnvironment: Environment
environments: Environment[] = [];
environmentForm: FormGroup;
textDDL: String = 'Select Environment';
private capabilities: Capability[] = [];
envCapabilities: Capability[] = [];
filteredCapabilities: Capability[] = [];
strategy: Strategy;
view: any;
menuState:string = 'out';
constructor(
private el:ElementRef,
private renderer:Renderer2,
private es: EnvironmentsService,
private router: Router,
private route: ActivatedRoute,
private fb: FormBuilder,
private environmentService: EnvironmentsService
) { }
ngOnInit(): void {
this.getEnvironments();
this.createForm();
}
createForm(){
this.environmentForm = this.fb.group({
name: ['',Validators.required]
})
}
updateEnvironment(){
this.newEnvironment = new Environment(
this.environmentForm.value.name
)
this.environmentService.updateEnvironment(this.environment.id, this.newEnvironment).subscribe(
(res) => {
console.log(this.newEnvironment)
this.router.navigate(['/'])
}
)
}
/**
* @method
* @returns this method will check if the form is valid, based on that it will either return an alert or call the update environment method
*/
onSubmit(){
if (!this.environmentForm.valid){
alert("form not valid");
return
}
this.updateEnvironment();
}
getEnvironments() {
this.es.getAllEnvironments().subscribe((data) => {
this.environments = data;
console.log(this.environments);
});
}
open() {
this.ddl.nativeElement.style.display = 'block';
this.isVisible(true);
}
close() {
this.ddl.nativeElement.style.display = 'none';
this.isVisible(false);
}
openClose() {
if (this.ddl.nativeElement.style.display == 'block') {
this.ddl.nativeElement.style.display = 'none';
} else {
this.ddl.nativeElement.style.display = 'block';
}
}
changeDDLtext(name: String) {
this.textDDL = name;
}
waitedText() {
setTimeout(() => {
this.textInvisible = true;
}, 500);
}
isVisible(flag: boolean): string {
if (flag) {
return 'd-block';
} else {
return 'd-none';
}
}
getEnvironment(id?: number) {
this.environment = this.environments.filter((x) => x.id == id)[0];
this.changeDDLtext(this.environment.name);
console.log(this.environment);
if(this.environment.strategy != null){
this.strategy = this.environment.strategy
}
this.envCapabilities = this.capabilities.filter(x => x.environment.id == id);
this.filteredCapabilities = this.envCapabilities;
//console.log(this.envCapabilities)
}
goToEnv(){
this.router.navigate(['/environment/create']);
}
goToEnvUpdate(id: number){
this.getEnvironment(id);
this.editModal.nativeElement.style.display = "block";
// this.router.navigate(['/environment/update'], {state: {environment: this.environment}})
}
openMenu() {
this.view = document.querySelector("#drop1")
if(this.view.style.display === "none") {
this.view.style.display = "block"
} else {
this.view.style.display = 'none'
}
}
openDelete(id: any) {
}
closeDelete() {
}
@HostListener('click', ['$event.target'])
onClick(target:any){
let item = this.el.nativeElement.querySelector('div');
}
toggleMenu(){
this.menuState = this.menuState === 'out' ? 'in' : 'out';
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/bZFQU.png" rel="nofollow noreferrer">here is how it looks</a></p>
| 3 | 7,935 |
Can't find error to not being able to compile into device
|
<p>I coded some scripts using some assets from the store and when i'm trying to compile the program to the Android phone i'm getting errors on compilation.</p>
<p>I changed SDK versions from 26 to 25, tried running the build on Graddle, Internal and Using Legacy SDK Tools, re built the entire project, updated assets, tried to normal build APK but it still gives out failure.</p>
<p>Error 1:</p>
<pre><code>FormatException: Input string was not in a correct format.
System.Number.StringToNumber (System.String str, System.Globalization.NumberStyles options, System.Number+NumberBuffer& number, System.Globalization.NumberFormatInfo info, System.Boolean parseDecimal) (at <d7ac571ca2d04b2f981d0d886fa067cf>:0)
System.Number.ParseInt32 (System.String s, System.Globalization.NumberStyles style, System.Globalization.NumberFormatInfo info) (at <d7ac571ca2d04b2f981d0d886fa067cf>:0)
System.Int32.Parse (System.String s, System.IFormatProvider provider) (at <d7ac571ca2d04b2f981d0d886fa067cf>:0)
System.Convert.ToInt32 (System.String value) (at <d7ac571ca2d04b2f981d0d886fa067cf>:0)
UnityEditor.Android.AndroidDeviceInfo.get_SDKVersion () (at <7cbc688ae1af4105929402a46c6a4414>:0)
UnityEditor.Android.AndroidDeviceInfo.HasSDKSupport (System.Int32 minimumVersion) (at <7cbc688ae1af4105929402a46c6a4414>:0)
UnityEditor.Android.AndroidDeploymentTargetsExtension+AndroidDeploymentTargetInfo.CheckTargetInternal (UnityEditor.Android.AndroidDeploymentTargetRequirements targetRequirements) (at <7cbc688ae1af4105929402a46c6a4414>:0)
UnityEditor.Android.AndroidDeploymentTargetsExtension+AndroidDeploymentTargetInfo.CheckTarget (UnityEditor.DeploymentTargetRequirements targetRequirements) (at <7cbc688ae1af4105929402a46c6a4414>:0)
UnityEditor.Android.PostProcessor.Tasks.CheckDevice.FindCompatibleDevices (UnityEditor.Android.AndroidDeploymentTargetRequirements targetRequirements, UnityEditor.DeploymentTargets.DeploymentTargetId targetId, System.Collections.Generic.List`1[T] knownDevices, System.Collections.Generic.List`1[UnityEditor.Android.PostProcessor.Tasks.CheckDevice+DeviceInfo]& compatibleDevices) (at <7cbc688ae1af4105929402a46c6a4414>:0)
UnityEditor.Android.PostProcessor.Tasks.CheckDevice.GetTargetDevices (UnityEditor.Android.ADB adb) (at <7cbc688ae1af4105929402a46c6a4414>:0)
UnityEditor.Android.PostProcessor.Tasks.CheckDevice.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <7cbc688ae1af4105929402a46c6a4414>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <7cbc688ae1af4105929402a46c6a4414>:0)
UnityEditor.Android.PostProcessAndroidPlayer.PrepareForBuild (UnityEditor.BuildOptions options, UnityEditor.BuildTarget target) (at <7cbc688ae1af4105929402a46c6a4414>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PrepareForBuild (UnityEditor.BuildOptions options, UnityEditor.BuildTarget target) (at <7cbc688ae1af4105929402a46c6a4414>:0)
UnityEditor.PostprocessBuildPlayer.PrepareForBuild (UnityEditor.BuildOptions options, UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:106)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
</code></pre>
<p>Error 2:</p>
<pre><code>Error building Player: FormatException: Input string was not in a correct format.
</code></pre>
<p>Error 3:</p>
<pre><code>Build completed with a result of 'Failed'
0x0000000141415DE8 (Unity) StackWalker::GetCurrentCallstack
0x000000014141C296 (Unity) StackWalker::ShowCallstack
0x00000001412FFB1B (Unity) GetStacktrace
0x000000014014325E (Unity) DebugStringToFile
0x00000001417873BD (Unity) DebugLogHandler_CUSTOM_Internal_Log
0x0000000043145590 (Mono JIT Code) (wrapper managed-to-native) UnityEngine.DebugLogHandler:Internal_Log (UnityEngine.LogType,string,UnityEngine.Object)
0x00000000431451F3 (Mono JIT Code) [DebugLogHandler.cs:10] UnityEngine.DebugLogHandler:LogFormat (UnityEngine.LogType,UnityEngine.Object,string,object[])
0x0000000043144A75 (Mono JIT Code) [Logger.cs:48] UnityEngine.Logger:Log (UnityEngine.LogType,object)
0x0000000043144709 (Mono JIT Code) [Debug.bindings.cs:117] UnityEngine.Debug:LogError (object)
0x0000000040DDE863 (Mono JIT Code) [BuildPlayerWindowBuildMethods.cs:190] UnityEditor.BuildPlayerWindow/DefaultBuildMethods:BuildPlayer (UnityEditor.BuildPlayerOptions)
0x0000000040DD601B (Mono JIT Code) [BuildPlayerWindowBuildMethods.cs:97] UnityEditor.BuildPlayerWindow:CallBuildMethods (bool,UnityEditor.BuildOptions)
0x0000000040DD57BB (Mono JIT Code) [BuildPlayerWindow.cs:174] UnityEditor.BuildPlayerWindow:BuildPlayerAndRun (bool)
0x0000000040DAA16B (Mono JIT Code) [BuildPlayerWindow.cs:926] UnityEditor.BuildPlayerWindow:GUIBuildButtons (UnityEditor.Modules.IBuildWindowExtension,bool,bool,bool,UnityEditor.Build.BuildPlatform)
0x0000000040D587BB (Mono JIT Code) [BuildPlayerWindow.cs:809] UnityEditor.BuildPlayerWindow:ShowBuildTargetSettings ()
0x0000000040C8A45B (Mono JIT Code) [BuildPlayerWindow.cs:411] UnityEditor.BuildPlayerWindow:OnGUI ()
0x00000000485FC8D0 (Mono JIT Code) (wrapper runtime-invoke) object:runtime_invoke_void__this__ (object,intptr,intptr,intptr)
0x00007FF8B273BE4B (mono-2.0-bdwgc) [mini-runtime.c:2809] mono_jit_runtime_invoke
0x00007FF8B26C1E32 (mono-2.0-bdwgc) [object.c:2919] do_runtime_invoke
0x00007FF8B26CB012 (mono-2.0-bdwgc) [object.c:3071] mono_runtime_invoke_checked
0x00007FF8B26CB7A9 (mono-2.0-bdwgc) [object.c:5262] mono_runtime_try_invoke_array
0x00007FF8B26CAFA6 (mono-2.0-bdwgc) [object.c:5140] mono_runtime_invoke_array_checked
0x00007FF8B266FED4 (mono-2.0-bdwgc) [icall.c:3358] ves_icall_InternalInvoke
0x000000003C6F64F6 (Mono JIT Code) (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
0x000000003C6F4F1B (Mono JIT Code) System.Reflection.MonoMethod:Invoke (object,System.Reflection.BindingFlags,System.Reflection.Binder,object[],System.Globalization.CultureInfo)
0x000000003EF8F56F (Mono JIT Code) System.Reflection.MethodBase:Invoke (object,object[])
0x0000000040497293 (Mono JIT Code) [HostView.cs:342] UnityEditor.HostView:Invoke (string,object)
0x00000000404970F3 (Mono JIT Code) [HostView.cs:337] UnityEditor.HostView:Invoke (string)
0x0000000040C88463 (Mono JIT Code) [HostView.cs:130] UnityEditor.HostView:OldOnGUI ()
0x00000000409B13DC (Mono JIT Code) [IMGUIContainer.cs:244] UnityEngine.Experimental.UIElements.IMGUIContainer:DoOnGUI (UnityEngine.Event,UnityEngine.Matrix4x4,UnityEngine.Rect,bool)
0x000000004098DA6B (Mono JIT Code) [IMGUIContainer.cs:440] UnityEngine.Experimental.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,UnityEngine.Matrix4x4,UnityEngine.Rect)
0x0000000040B148D3 (Mono JIT Code) [IMGUIContainer.cs:421] UnityEngine.Experimental.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event)
0x000000004048E2FB (Mono JIT Code) [IMGUIContainer.cs:401] UnityEngine.Experimental.UIElements.IMGUIContainer:HandleEvent (UnityEngine.Experimental.UIElements.EventBase)
0x000000003F4A47E4 (Mono JIT Code) [EventDispatcher.cs:516] UnityEngine.Experimental.UIElements.EventDispatcher:ProcessEvent (UnityEngine.Experimental.UIElements.EventBase,UnityEngine.Experimental.UIElements.IPanel)
0x000000003F1BF0FB (Mono JIT Code) [EventDispatcher.cs:308] UnityEngine.Experimental.UIElements.EventDispatcher:Dispatch (UnityEngine.Experimental.UIElements.EventBase,UnityEngine.Experimental.UIElements.IPanel,UnityEngine.Experimental.UIElements.DispatchMode)
0x000000003F1BEBC3 (Mono JIT Code) [Panel.cs:177] UnityEngine.Experimental.UIElements.BaseVisualElementPanel:SendEvent (UnityEngine.Experimental.UIElements.EventBase,UnityEngine.Experimental.UIElements.DispatchMode)
0x000000004091F653 (Mono JIT Code) [UIElementsUtility.cs:248] UnityEngine.Experimental.UIElements.UIElementsUtility:DoDispatch (UnityEngine.Experimental.UIElements.BaseVisualElementPanel)
0x000000004094F8FB (Mono JIT Code) [UIElementsUtility.cs:68] UnityEngine.Experimental.UIElements.UIElementsUtility:ProcessEvent (int,intptr)
0x000000004094F264 (Mono JIT Code) [GUIUtility.cs:179] UnityEngine.GUIUtility:ProcessEvent (int,intptr)
0x000000004094F483 (Mono JIT Code) (wrapper runtime-invoke) <Module>:runtime_invoke_bool_int_intptr (object,intptr,intptr,intptr)
0x00007FF8B273BE4B (mono-2.0-bdwgc) [mini-runtime.c:2809] mono_jit_runtime_invoke
0x00007FF8B26C1E32 (mono-2.0-bdwgc) [object.c:2919] do_runtime_invoke
0x00007FF8B26CAE3F (mono-2.0-bdwgc) [object.c:2966] mono_runtime_invoke
0x0000000140C02DDA (Unity) scripting_method_invoke
0x0000000140BF33EA (Unity) ScriptingInvocation::Invoke
0x0000000140BED44A (Unity) ScriptingInvocation::Invoke<bool>
0x000000014042E60C (Unity) Scripting::UnityEngine::GUIUtilityProxy::ProcessEvent
0x000000014129171C (Unity) GUIView::ProcessRetainedMode
0x000000014147ABA0 (Unity) GUIView::OnInputEvent
0x000000014129162C (Unity) GUIView::ProcessInputEvent
0x000000014147C23C (Unity) GUIView::ProcessEventMessages
0x00000001414720CF (Unity) GUIView::GUIViewWndProc
0x00007FF901476D41 (USER32) CallWindowProcW
0x00007FF901476713 (USER32) DispatchMessageW
0x000000014149892F (Unity) MainMessageLoop
0x000000014149A426 (Unity) WinMain
0x000000014247F7EA (Unity) __scrt_common_main_seh
0x00007FF9011A4034 (KERNEL32) BaseThreadInitThunk
0x00007FF901873691 (ntdll) RtlUserThreadStart
</code></pre>
<p>Error 4:</p>
<pre><code>UnityEditor.BuildPlayerWindow+BuildMethodException: 2 errors
at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x00234] in C:\buildslave\unity\build\Editor\Mono\BuildPlayerWindowBuildMethods.cs:190
at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x0007f] in C:\buildslave\unity\build\Editor\Mono\BuildPlayerWindowBuildMethods.cs:96
0x0000000141415DE8 (Unity) StackWalker::GetCurrentCallstack
0x000000014141C296 (Unity) StackWalker::ShowCallstack
0x00000001412FFB1B (Unity) GetStacktrace
0x000000014014325E (Unity) DebugStringToFile
0x00000001417873BD (Unity) DebugLogHandler_CUSTOM_Internal_Log
0x0000000043145590 (Mono JIT Code) (wrapper managed-to-native) UnityEngine.DebugLogHandler:Internal_Log (UnityEngine.LogType,string,UnityEngine.Object)
0x00000000431451F3 (Mono JIT Code) [DebugLogHandler.cs:10] UnityEngine.DebugLogHandler:LogFormat (UnityEngine.LogType,UnityEngine.Object,string,object[])
0x0000000043144A75 (Mono JIT Code) [Logger.cs:48] UnityEngine.Logger:Log (UnityEngine.LogType,object)
0x0000000043144709 (Mono JIT Code) [Debug.bindings.cs:117] UnityEngine.Debug:LogError (object)
0x0000000040DD619B (Mono JIT Code) [BuildPlayerWindowBuildMethods.cs:102] UnityEditor.BuildPlayerWindow:CallBuildMethods (bool,UnityEditor.BuildOptions)
0x0000000040DD57BB (Mono JIT Code) [BuildPlayerWindow.cs:174] UnityEditor.BuildPlayerWindow:BuildPlayerAndRun (bool)
0x0000000040DAA16B (Mono JIT Code) [BuildPlayerWindow.cs:926] UnityEditor.BuildPlayerWindow:GUIBuildButtons (UnityEditor.Modules.IBuildWindowExtension,bool,bool,bool,UnityEditor.Build.BuildPlatform)
0x0000000040D587BB (Mono JIT Code) [BuildPlayerWindow.cs:809] UnityEditor.BuildPlayerWindow:ShowBuildTargetSettings ()
0x0000000040C8A45B (Mono JIT Code) [BuildPlayerWindow.cs:411] UnityEditor.BuildPlayerWindow:OnGUI ()
0x00000000485FC8D0 (Mono JIT Code) (wrapper runtime-invoke) object:runtime_invoke_void__this__ (object,intptr,intptr,intptr)
0x00007FF8B273BE4B (mono-2.0-bdwgc) [mini-runtime.c:2809] mono_jit_runtime_invoke
0x00007FF8B26C1E32 (mono-2.0-bdwgc) [object.c:2919] do_runtime_invoke
0x00007FF8B26CB012 (mono-2.0-bdwgc) [object.c:3071] mono_runtime_invoke_checked
0x00007FF8B26CB7A9 (mono-2.0-bdwgc) [object.c:5262] mono_runtime_try_invoke_array
0x00007FF8B26CAFA6 (mono-2.0-bdwgc) [object.c:5140] mono_runtime_invoke_array_checked
0x00007FF8B266FED4 (mono-2.0-bdwgc) [icall.c:3358] ves_icall_InternalInvoke
0x000000003C6F64F6 (Mono JIT Code) (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
0x000000003C6F4F1B (Mono JIT Code) System.Reflection.MonoMethod:Invoke (object,System.Reflection.BindingFlags,System.Reflection.Binder,object[],System.Globalization.CultureInfo)
0x000000003EF8F56F (Mono JIT Code) System.Reflection.MethodBase:Invoke (object,object[])
0x0000000040497293 (Mono JIT Code) [HostView.cs:342] UnityEditor.HostView:Invoke (string,object)
0x00000000404970F3 (Mono JIT Code) [HostView.cs:337] UnityEditor.HostView:Invoke (string)
0x0000000040C88463 (Mono JIT Code) [HostView.cs:130] UnityEditor.HostView:OldOnGUI ()
0x00000000409B13DC (Mono JIT Code) [IMGUIContainer.cs:244] UnityEngine.Experimental.UIElements.IMGUIContainer:DoOnGUI (UnityEngine.Event,UnityEngine.Matrix4x4,UnityEngine.Rect,bool)
0x000000004098DA6B (Mono JIT Code) [IMGUIContainer.cs:440] UnityEngine.Experimental.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,UnityEngine.Matrix4x4,UnityEngine.Rect)
0x0000000040B148D3 (Mono JIT Code) [IMGUIContainer.cs:421] UnityEngine.Experimental.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event)
0x000000004048E2FB (Mono JIT Code) [IMGUIContainer.cs:401] UnityEngine.Experimental.UIElements.IMGUIContainer:HandleEvent (UnityEngine.Experimental.UIElements.EventBase)
0x000000003F4A47E4 (Mono JIT Code) [EventDispatcher.cs:516] UnityEngine.Experimental.UIElements.EventDispatcher:ProcessEvent (UnityEngine.Experimental.UIElements.EventBase,UnityEngine.Experimental.UIElements.IPanel)
0x000000003F1BF0FB (Mono JIT Code) [EventDispatcher.cs:308] UnityEngine.Experimental.UIElements.EventDispatcher:Dispatch (UnityEngine.Experimental.UIElements.EventBase,UnityEngine.Experimental.UIElements.IPanel,UnityEngine.Experimental.UIElements.DispatchMode)
0x000000003F1BEBC3 (Mono JIT Code) [Panel.cs:177] UnityEngine.Experimental.UIElements.BaseVisualElementPanel:SendEvent (UnityEngine.Experimental.UIElements.EventBase,UnityEngine.Experimental.UIElements.DispatchMode)
0x000000004091F653 (Mono JIT Code) [UIElementsUtility.cs:248] UnityEngine.Experimental.UIElements.UIElementsUtility:DoDispatch (UnityEngine.Experimental.UIElements.BaseVisualElementPanel)
0x000000004094F8FB (Mono JIT Code) [UIElementsUtility.cs:68] UnityEngine.Experimental.UIElements.UIElementsUtility:ProcessEvent (int,intptr)
0x000000004094F264 (Mono JIT Code) [GUIUtility.cs:179] UnityEngine.GUIUtility:ProcessEvent (int,intptr)
0x000000004094F483 (Mono JIT Code) (wrapper runtime-invoke) <Module>:runtime_invoke_bool_int_intptr (object,intptr,intptr,intptr)
0x00007FF8B273BE4B (mono-2.0-bdwgc) [mini-runtime.c:2809] mono_jit_runtime_invoke
0x00007FF8B26C1E32 (mono-2.0-bdwgc) [object.c:2919] do_runtime_invoke
0x00007FF8B26CAE3F (mono-2.0-bdwgc) [object.c:2966] mono_runtime_invoke
0x0000000140C02DDA (Unity) scripting_method_invoke
0x0000000140BF33EA (Unity) ScriptingInvocation::Invoke
0x0000000140BED44A (Unity) ScriptingInvocation::Invoke<bool>
0x000000014042E60C (Unity) Scripting::UnityEngine::GUIUtilityProxy::ProcessEvent
0x000000014129171C (Unity) GUIView::ProcessRetainedMode
0x000000014147ABA0 (Unity) GUIView::OnInputEvent
0x000000014129162C (Unity) GUIView::ProcessInputEvent
0x000000014147C23C (Unity) GUIView::ProcessEventMessages
0x00000001414720CF (Unity) GUIView::GUIViewWndProc
0x00007FF901476D41 (USER32) CallWindowProcW
0x00007FF901476713 (USER32) DispatchMessageW
0x000000014149892F (Unity) MainMessageLoop
0x000000014149A426 (Unity) WinMain
0x000000014247F7EA (Unity) __scrt_common_main_seh
0x00007FF9011A4034 (KERNEL32) BaseThreadInitThunk
0x00007FF901873691 (ntdll) RtlUserThreadStart
</code></pre>
<p>My expected output is to be able to compile the APK into the phone for testing controls and further developing.</p>
| 3 | 5,734 |
Couldn't find World with 'id'=
|
<p>I have a World parent object and a State child object. I'm trying to create a new State object and rails isn't finding the world id. I'm trying to link to the new state form from the world show page, and the url shows <code>.../worlds/1/states/new</code> so why is this not picking up on the parent id? The error is supposedly coming from this line in the controller <code>@world = World.find(params[:id])</code>. I have tried using <code>(params[:world_id])</code> even.</p>
<p>For brevity I'm only posting the relevant code here. </p>
<p>world.rb</p>
<pre><code>class World < ApplicationRecord
belongs_to :user
has_many :states
end
</code></pre>
<p>state.rb</p>
<pre><code>class State < ApplicationRecord
belongs_to :world
belongs_to :user
end
</code></pre>
<p>states_controller.rb</p>
<pre><code>class StatesController < ApplicationController
before_action :set_state, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@states = State.all
end
def new
@world = World.find(params[:id])
@state = @world.states.build
end
def create
@world = World.find(params[:id])
@state = @world.states.build(state_params)
@state.user = current_user
respond_to do |format|
if @state.save
format.html { redirect_to @state, notice: 'State was successfully created.' }
else
format.html { render :new }
end
end
end
private
def set_state
@state = State.find(params[:id])
end
def state_params
params.require(:state).permit(:name, :summary, :history, :population, :inception, :life_expectancy, :land_mass,
:climate, :industry, :education, :mythology, :law, :culture, :world_id, :user_id)
end
end
</code></pre>
<p>The link to the new state form in worlds/show.html.erb:</p>
<pre><code><%= link_to 'New State', new_world_state_path(@world) %>
</code></pre>
<p>routes.rb</p>
<pre><code>Rails.application.routes.draw do
resources :states
resources :worlds
devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register' }
root to: "home#index"
resources :users
resources :worlds do
resources :states
end
end
</code></pre>
<p>states/_form.html.erb</p>
<pre><code><div class="form">
<%= form_for(state) do |f| %>
<% if state.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(world.errors.count, "error") %> prohibited this state from being saved:</h2>
<ul>
<% state.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field :name, placeholder: 'Name' %><br />
<fieldset>
<legend>Basic Info</legend>
<%= f.text_area :summary, placeholder: 'Summary About', rows: 6 %><br />
<%= f.text_area :history, placeholder: 'History', rows: 6 %><br />
<%= f.text_area :climate, placeholder: 'Climate', rows: 3 %><br />
<%= f.text_area :industry, placeholder: 'Industry', rows: 3 %><br />
<%= f.text_area :education, placeholder: 'Education', rows: 3 %><br />
<%= f.text_area :culture, placeholder: 'Culture', rows: 3 %><br />
<%= f.text_area :law, placeholder: 'Legal System, Crime & Punishment', rows: 3 %><br />
<%= f.text_area :mythology, placeholder: 'Mythology', rows: 3 %><br />
</fieldset>
<fieldset>
<legend>Quick Stats</legend>
<%= f.text_field :inception, placeholder: 'Inception' %><br />
<%= f.text_field :population, placeholder: 'Population' %><br />
<%= f.text_field :life_expectancy, placeholder: 'Ave. Life Expectance' %><br />
<%= f.text_field :land_mass, placeholder: 'Land Mass' %><br />
</fieldset>
<p><%= f.submit %></p>
<% end %>
</div>
</code></pre>
<p>rails console results when clicking 'New State' link</p>
<pre><code>Started GET "/worlds/1/states/new" for 70.196.17.76 at 2017-05-22 13:43:47 +0000
Cannot render console from 70.196.17.76! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by StatesController#new as HTML
Parameters: {"world_id"=>"1"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]]
World Load (0.1ms) SELECT "worlds".* FROM "worlds" WHERE "worlds"."id" = ? LIMIT ? [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 3ms (ActiveRecord: 0.4ms)
ActiveRecord::RecordNotFound (Couldn't find World with 'id'=):
app/controllers/states_controller.rb:13:in `new'
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (4.7ms)
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.6ms)
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.1ms)
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (36.6ms)
</code></pre>
| 3 | 2,656 |
Parallax effect is laggy an jumps
|
<p>Ok. Im trying to make a parallax website that works on every browser. I have achieved the effect on all browsers but it is laggy and jumpy in some browsers. Is there any way to make it smooth?</p>
<p>Here is 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>function Draw(){
requestAnimationFrame(Draw);
scrollEvent();
}
Draw();
function scrollEvent(){
var height = $(window).height();
if($(document).scrollTop() <= height){
$('#home').css('transform', 'translate3d(0, ' + ($(document).scrollTop() + 'px, 0)'));
$('#about').css('transform', 'translate3d(0, ' + ($(document).scrollTop() - height + 'px, 0)'));
}else if($(document).scrollTop() <= 2*height){
$('#about').css('transform', 'translate3d(0, ' + ($(document).scrollTop() -height + 'px, 0)'));
$('#gallery').css('transform', 'translate3d(0, ' + ($(document).scrollTop() - 2*height + 'px, 0)'));
}else if($(document).scrollTop() <= 3*height){
$('#gallery').css('transform', 'translate3d(0, ' + ($(document).scrollTop() -2*height + 'px, 0)'));
$('#blog').css('transform', 'translate3d(0, ' + ($(document).scrollTop() - 3*height + 'px, 0)'));
}else if($(document).scrollTop() <= 4*height){
$('#blog').css('transform', 'translate3d(0, ' + ($(document).scrollTop() -3*height+ 'px, 0)'));
$('#contact').css('transform', 'translate3d(0, ' + ($(document).scrollTop() - 4*height + 'px, 0)'));
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*...............................fonts..................................*/
@font-face {
font-family: 'aka-acid-typogroteskregular';
src: url('../fonts/actypogrotesk-webfont.eot');
src: url('../fonts/actypogrotesk-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/actypogrotesk-webfont.woff2') format('woff2'),
url('../fonts/actypogrotesk-webfont.woff') format('woff'),
url('../fonts/actypogrotesk-webfont.ttf') format('truetype'),
url('../fonts/actypogrotesk-webfont.svg#aka-acid-typogroteskregular') format('svg');
font-weight: normal;
font-style: normal;
}
.font{
font-family: 'aka-acid-typogroteskregular';
}
/*...............................colors..................................*/
.black{
color:#000000;
}
.white{
color:#ffffff;
}
/*...............................text-centering..................................*/
.text-center{
text-align:center;
}
.text-right{
text-align:right;
}
/*...............................navigation..................................*/
nav{
padding-right:100px;
}
nav ul{
list-style:none;
}
nav ul li{
padding:30px 20px 20px 20px;
cursor:pointer;
}
nav ul li:hover{
color:#DCDCDC;
}
*{
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
backface-visibility: hidden;
padding:0;
margin:0;
letter-spacing:2px;
}
.inline{
display:inline-block;
*display:inline;
zoom:1;
}
html, body
{
width:100%;
height:100%;
}
.cont{
width:100%;
height:100%;
overflow:hidden;
position:relative;
webkit-overflow-scrolling:touch;
}
.rlt-container{
position:absolute;
width:100%;
height:100%;
display:block;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-repeat: no-repeat;
background-position:center top;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
backface-visibility: hidden;
}
.first{
-webkit-transform: translate3d(0, 0, 0);
-moz-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.others{
-webkit-transform: translate3d(0, 100, 0);
-moz-transform: translate3d(0, 100, 0);
-ms-transform: translate3d(0, 100, 0);
transform: translate3d(0, 100, 0);
}
.overlay123{
position:absolute;
width:100%;
height:100%;
z-index:999;
background-image: url('../media/backgrounds/dark_overlay.png');
}
.title-cont{
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
top:50%;
margin-top:-49.5px;
}
.title{
font-size:82px;
font-weight: 200;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<?php include 'incl/base_url.php';?>
<link rel="stylesheet" type="text/css" href="css/global.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/ScrollToPlugin.min.js"></script>
</head>
<body>
<!--Home-->
<div class="cont">
<div class="overlay123">
<header>
<?php include 'incl/nav.php';?>
</header>
<div class="title-cont text-center">
<h2 class="title font white">Liokoki</h2>
</div>
</div>
<div id="home" class="rlt-container first" style="background-image: url('media/backgrounds/MG_0069.jpg');">
</div>
</div>
<!--About-->
<div class="cont">
<div class="overlay123">
<div class="title-cont text-center">
<h2 class="title font white">About</h2>
</div>
</div>
<div id="about" class="rlt-container others" style="background-image: url('media/backgrounds/MG_0129.jpg');">
</div>
</div>
<!--Gallery-->
<div class="cont">
<div class="overlay123">
<div class="title-cont text-center">
<h2 class="title font white">Gallery</h2>
</div>
</div>
<div id="gallery" class="rlt-container others" style="background-image: url('media/backgrounds/MG_0107.jpg');">
</div>
</div>
<!--blog-->
<div class="cont">
<div class="overlay123">
<div class="title-cont text-center">
<h2 class="title font white">Blog</h2>
</div>
</div>
<div id="blog" class="rlt-container others" style="background-image: url('media/backgrounds/MG_0142.jpg');">
</div>
</div>
<!--Contact-->
<div class="cont">
<div class="overlay123">
<div class="title-cont text-center">
<h2 class="title font white">Contact</h2>
</div>
</div>
<div id="contact" class="rlt-container others" style="background-image: url('media/backgrounds/DJI_0011.jpg');">
</div>
</div>
<script src="js/effects.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| 3 | 3,181 |
how to append data one by one in html table using jquery
|
<p>my problem is when i insert a new data it append on the same <code><td></code> of the <code><table></code>, i want to append data in a new block , so that the data/item is displayed one by one just like snapdeal ex:-<a href="http://www.snapdeal.com/search?keyword=micromax&santizedKeyword=&catId=&categoryId=175&suggested=true&vertical=p&noOfResults=20&clickSrc=suggested&lastKeyword=&prodCatId=&changeBackToAll=false&foundInAll=false&categoryIdSearched=&cityPageUrl=&url=&utmContent=&dealDetail=" rel="nofollow">http://www.snapdeal.com/</a>.</p>
<p>Sorry for my bad english. </p>
<p><strong>display-posts.html</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AdPortal</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<div class="header">
<div>
<img class="logo" src="images/zuikr.png" alt="logo" />
</div>
<div class="post_ad">
<ul class="header_nav">
<a href="http://localhost/adportal/login.html"><li class="header_nav_link">post a free ad</li></a>
</ul>
</div>
</div>
<div class="nav">
<ul class="nav_link">
<div class="nav_link_div"><a href="http://localhost/adportal/index.html"><li class="nav_link_list">HOME</li></a></div>
<div class="nav_link_div"><a href="#"><li class="nav_link_list">CONTACT US</li></a></div>
<div class="nav_link_div"><a href="#"><li class="nav_link_list">ABOUT</li></a></div>
</ul>
</div>
<div class="display_posts">
<img src="" alt="post" id="path" class="post_image">
<table class="post_data">
<tr >
<td colspan = "2">
<p style="text-align:center;font-weight:bold">Followings are the Details of This Ad</p></td></tr>
<tr><td>ID of Ad is</td><td id="post_id"></td></tr>
<tr><td>Title of Ad is:</td><td id="post_title"></td></tr>
<tr><td>Model of Ad is:</td><td id="post_model"></td></tr>
<tr><td>Price of Ad is:</td><td id="post_price"></td></tr>
<tr><td>Description about Ad is:</td><td id="post_description"></td></tr>
<tr><td>Name:</td><td id="post_name"></td></tr>
<tr><td>Your communicating email is:</td><td id="post_email"></td></tr>
<tr><td>Contact Number:</td><td id="post_phone"></td></tr>
<tr><td>city:</td><td id="post_city"></td></tr>
<tr><td>Category of Your post is:</td><td id="post_category"></td></tr>
</table>
</div>
</div>
<footer>
<p id="company_name"></p>
</footer>
</div>
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
<script src="js/company-name.js"></script>
<script src="js/display-posts.js"></script>
</body>
</html>
</code></pre>
<p><strong>display-posts.js</strong></p>
<pre><code>$(document).ready(function() {
$.ajax({
url: 'php/display-posts.php',
type: 'GET',
success:function(data)
{
var result = $.parseJSON(data);
$.each(result, function(key, value) {
$.each(value, function(key, value) {
if (key === 'id') { $('#post_id').append(value); };
if (key === 'title') { $('#post_title').append(value); };
if (key === 'price') { $('#post_price').append(value); };
if (key === 'model') { $('#post_model').append(value); };
if (key === 'description') { $('#post_description').append(value); };
if (key === 'name') { $('#post_name').append(value); };
if (key === 'email') { $('#post_email').append(value); };
if (key === 'phone') { $('#post_phone').append(value); };
if (key === 'city') { $('#post_city').append(value); };
if (key === 'category') { $('#post_category').append(value); };
if (key === 'path') { $('#path').attr('src', value.slice(3) ) };
});
});
}
});
});
</code></pre>
<p><strong>display-posts.php</strong></p>
<pre><code><?php
session_start();
require_once 'database.php';
$category = $_SESSION['category'];
$data = array();
$query = $dbh->prepare("SELECT * FROM posts WHERE category = ?");
$query->execute(array($category));
$data = $query->fetchall(PDO::FETCH_ASSOC);
foreach ($query as $key => $value) {
$data[$key] = $value;
}
$result = json_encode($data);
echo $result;
</code></pre>
| 3 | 3,168 |
DismissViewController sometimes causes the program to freeze or crash
|
<p>I have the following MonoTouch program:</p>
<pre><code>using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System;
namespace Experiment
{
// This is just for the example, I use a singleton in my app to do this.
public class AppSettings
{
public static bool IsLoggedIn = false;
}
[Register ("AppDelegate")]
public class AppDelegate : UIApplicationDelegate
{
UIWindow window;
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
UIViewController baseViewController = new RootViewController();
window = new UIWindow(UIScreen.MainScreen.Bounds);
window.AddSubview(baseViewController.View);
window.MakeKeyAndVisible();
return true;
}
static void Main(string[] args)
{
UIApplication.Main(args, null, "AppDelegate");
}
}
public class RootViewController : UITableViewController
{
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if (!AppSettings.IsLoggedIn) {
this.PresentViewController(new LoginPopupController(), false, () => {});
}
}
}
public class LoginPopupController : UIViewController
{
public override void LoadView()
{
View = new UIView(UIScreen.MainScreen.ApplicationFrame);
View.BackgroundColor = UIColor.White;
UIButton button = new UIButton();
button.SetTitle("press me", UIControlState.Normal);
button.Frame = new RectangleF(50, 50, 80, 80);
button.TouchUpInside += delegate {
LoginSucceeded();
};
button.BackgroundColor = UIColor.Purple;
View.AddSubview(button);
}
public void LoginSucceeded()
{
AppSettings.IsLoggedIn = true;
Console.WriteLine("This line causes multiple problems at random");
DismissViewController(true, () => {});
}
}
}
</code></pre>
<p>It has two controllers the RootViewController and the LoginPopupController. The FinishedLoading method adds the RootViewController to the window. The RootViewController in the ViewDidAppear method checks if the app is logged in. If not, it will present the LoginPopupController. </p>
<p>The LoginPopupController has a button, which when pressed will set IsLoggedIn to true, and dismiss itself.</p>
<p>Basically, I want a login window to appear if the user isn't logged in, and then dismiss itself after it has entered login details into a singleton settings object. </p>
<hr>
<p>However, the app is very unreliable at the moment. Pressing the "press me" button can cause the following to happen at random:</p>
<ul>
<li>Work as expected</li>
<li>Freeze the app</li>
<li>Crash the app</li>
<li>Do nothing on first press, crash the app on the second press</li>
</ul>
<p>The <code>Console.WriteLine</code> line has a big effect on this - if you remove it the code succeeds more often (but not always).</p>
<p>Can anyone figure out what is causing this problem? It seems like a race condition (as the results change between runs), however I can't figure out what could be causing that.</p>
<p>I'm running the code on the simulator using iOS 5.1. I have MonoTouch version 5.2.10 installed with Mono 2.10.8.</p>
| 3 | 1,320 |
How would I stop an random colour randomise from picking the same colour twice
|
<pre><code><script>
function randomColour(){
var colour=[];
colour[0]= '#edf2fb';
colour[1]= '#d7e3fc';
colour[3]= '#c1d3fe';
colour[4]= '#d1d1d1';
colour[5]= '#e1dbd6';
colour[6]= '#e2e2e2';
colour[7]= '#f9f6f2';
colour[8]='#ffc09f';
colour[9]='#ffee93';
colour[10]='#fcf5c7';
colour[11]='#a0ced9';
colour[12]='#adf7b6';
colour[13]='#809bce';
colour[14]='#95b8d1';
colour[15]='#b8e0d2';
colour[16]='#d6eadf';
colour[17]='#eac4d5';
colour[18]='#e8d1c5';
colour[19]='#eddcd2';
colour[20]='#fff1e6';
colour[21]='#f0efeb';
colour[22]='#eeddd3';
colour[23]='#e8dff5';
colour[24]='#fce1e4';
colour[25]='#fcf4dd';
colour[26]='#ddedea';
colour[27]='#daeaf6';
colour[28]='#d3ab9e';
colour[29]='#eac9c1';
colour[30]='#ebd8d0';
colour[31]='#ffe5ec';
colour[32]='#ffc2d1';
colour[33]='#ceb5b7';
colour[35]='#b5d6d6';
colour[36]='#f2f5ff';
colour[37]='#efcfe3';
colour[38]='#eaf2d7';
colour[39]='#b3dee2';
colour[40]='#f8ad9d';
colour[41]='#fbc4ab';
colour[42]='#ffdab9';
colour[43]='#cdb4db';
colour[44]='#ffc8dd';
colour[45]='#ffafcc';
colour[46]='#bde0fe';
colour[47]='#a2d2ff';
colour[48]='#fdffb6';
colour[49]='#caffbf';
colour[50]='#9bf6ff';
colour[51]='#a0c4ff';
colour[52]='#ffc6ff';
colour[53]='#a7bed3';
colour[54]='#c6e2e9';
colour[55]='#f1ffc4';
colour[56]='#ffcaaf';
colour[57]='#dab894';
colour[58]='#fec7bc';
colour[59]='#fcf5ee';
var pick= Math.floor(Math.random()*60);
var test = document.getElementById("colorpad");
test.style.backgroundColor = colour[pick];
return colour[pick];
}
</script>
</code></pre>
<p>I would like to know on how I would be able to stop this random colour picker from choosing the same colour twice because it is currently doing this when I want it to pick another random colour. I do not know why this is occurring, what should I implement into my code to stop this from occurring.</p>
| 3 | 1,352 |
Eliminate duplicates based on 2 dates in a dataframe
|
<p>I have this sample dataframe:</p>
<pre><code>df <- data.frame(ID = c("5","5","5","5","5","5" ,"5" ,"5","5","5","5","14","14","14","14" ,"14","14"),
Date1= c("22/07/2014","22/07/2014","22/07/2014"
,"22/07/2014"
,"22/07/2014"
,"22/07/2014"
,"22/07/2014"
,"22/07/2014"
,"22/07/2014"
,"22/07/2014"
,"22/07/2014"
,"08/11/2016"
, "08/11/2016"
, "08/11/2016"
, "08/11/2016"
, "08/11/2016"
, "08/11/2016"),
Date2= c("01/01/2011"
,"01/08/2011"
,"01/12/2010"
,"10/11/2015"
,"22/07/2014"
,"01/01/2013"
,"23/04/2014"
,"01/01/2006"
,"01/01/2013"
,"01/10/2012"
,"01/08/2012"
,"14/04/2015"
,"01/10/2008"
,"01/10/2008"
,"14/05/2015"
,"11/04/2015"
,"05/10/2008"),
stringsAsFactors = F)
</code></pre>
<p>where I have each ID repeated several times. I need to get a dataframe with only 1 line per ID. As you can see, each patient has only one date in column df$date1, so the condition to select 1 row per patient would be: to pick the <em><strong>closest</strong></em> date between date 1 and date 2.</p>
<p>How could I do that?</p>
<p>Thansk</p>
| 3 | 1,637 |
How can I use the Kivy Filechooser to display server's files (remote computer)?
|
<p>I'm creating a client server program with the idea of a shared files cloud.
I want to add a screen which is displaying the server side files (to create a specific folder on the server which is the "cloud" and display it on the client's side, the client should be able to edit files, add files and open files).</p>
<p>Here is what I have for now (only the user's side is working).</p>
<p>--- Client ---</p>
<pre><code>import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivy.lang import Builder
import os
import socket
import sys
s = socket.socket()
PORT = 9898
s.connect(('127.0.0.1', PORT))
class P(FloatLayout):
pass
def show_popup():
show = P()
popupWindow = Popup(title="", content=show, size_hint=(None, None), size=(400, 400))
popupWindow.open()
class UserFileManager(BoxLayout):
def open(self, path, filename):
try:
os.startfile(filename[0])
except:
show_popup()
def selected(self, filename):
try:
print ("selected: %s" % filename[0])
except:
pass
def send(self, filename):
s.send('SEND'.encode('utf-8'))
with open(filename, 'rb') as f:
file_name_without_path = filename.split('\\')
file_name_without_path = file_name_without_path[len(file_name_without_path)-1]
s.send(file_name_without_path.encode('utf-8')) #send name
filesize = os.path.getsize(filename)
s.send(str(filesize).encode('utf-8')) # send size
bytesToSend = f.read(1024)
s.send(bytesToSend)
bytes_sent = 0
while len(bytesToSend) != 0:
bytesToSend = f.read(1024)
bytes_sent += len(bytesToSend)
s.send(bytesToSend)
class MyApp(App):
def build(self):
return UserFileManager()
if __name__ == '__main__':
MyApp().run()
# Close the connection from client side
s.close()
</code></pre>
<p>---- my.kv file ----</p>
<pre><code><RoundedButton@Button>:
background_color : (0,0,0,0)
background_normal: ''
back_color : (1,0,1,1)
border_radius: [18]
canvas.before:
Color:
rgba: self.back_color
RoundedRectangle:
size: self.size
pos: self.pos
radius: self.border_radius
<UserFileManager>:
id: my_widget
GridLayout:
rows: 3
GridLayout:
rows: 1
size_hint: 1, 0.1
Label:
text: "Welcome To RonDrive"
GridLayout:
rows: 1
size: root.width, root.height - 100
FileChooserListView:
id: filechooser
on_selection: my_widget.selected(filechooser.selection)
FloatLayout:
size_hint: 1, 0.2
RoundedButton
text: "open file"
pos_hint: {"x":0.01, "top":1}
back_color : (41/255, 21/255, 228/255, 1)
size_hint: 0.1, 0.45
on_release: my_widget.open(filechooser.path, filechooser.selection)
RoundedButton
text: " Upload File"
pos_hint: {"x":0.115, "top":1}
size_hint: 0.1, 0.45
back_color : (41/255, 21/255, 228/255, 1)
on_release: my_widget.send(filechooser.selection[0])
RoundedButton
text: "Nothing"
size_hint: 0.1, 0.45
pos_hint: {"x":0.01, "top":0.5}
back_color : (41/255, 21/255, 228/255, 1)
<P>:
Label:
text: "You Haven't Chose Any File"
size_hint: 0.6, 0.2
pos_hint: {"x":0.2, "top": 1}
Button:
text: "OK, Got It"
size_hint: 0.8, 0.2
pos_hint: {"x":0.1, "y": 0.1}
</code></pre>
<p>--- server ---</p>
<pre><code>import socket
import threading
import os
def UploadFile(client):
filename = client.recv(1024).decode('utf-8')
filesize = client.recv(1024).decode('utf-8')
filesize = int(filesize)
new_file_path = 'C:\\Users\\רון\\PycharmProjects\\untitled1\\RonDrive\\' + filename
f = open(new_file_path, 'wb')
data = client.recv(1024)
totalRecv = len(data)
f.write(data)
while totalRecv < filesize:
data = client.recv(1024)
totalRecv += len(data)
print(str((totalRecv / filesize) * 100) + "%")
f.write(data)
f.close()
def ReciveClientRequest(client):
request = client.recv(1024).decode("utf-8")
if request == "SEND":
print ('UPLOAD')
UploadFile(client)
def Main():
host = '0.0.0.0'
port = 9898
s = socket.socket()
s.bind((host, port))
s.listen(1)
client, addr = s.accept()
while True:
ReciveClientRequest(client)
s.close()
if __name__ == '__main__':
Main()
</code></pre>
| 3 | 2,468 |
How to have a delete flow in Mule Application?
|
<p>I just came to know about this Mule ESB and started playing with it. I checked few youtube videos and trying a basic flow which will just 1. delete a file or folder, 2. copy a file from source to destination, 3. move a file from source to destination, 4. logs a message, but unfortunately none is working.
It Says my application deployed without any errors but nothing is working
Below is generated XML when i drag n drop a "file copy" from the palatte.
</p>
<pre><code><mule xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd">
<flow name="sampleFlow" doc:id="06ea9943-8a7f-46a2-807a-1dff0f99d05b" >
<file:delete doc:name="Delete" doc:id="16275baf-bbcd-437a-b511-faee072e9a17" path="D:\source"/>
</flow>
</mule>
</code></pre>
<p>Below is the console log:</p>
<pre><code>MULE_HOME is set to E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule
MULE_BASE is set to E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule
--> Wrapper Started as Console
Java Service Wrapper Standard Edition 64-bit 3.5.35
Copyright (C) 1999-2018 Tanuki Software, Ltd. All Rights Reserved.
http://wrapper.tanukisoftware.com
Licensed to MuleSoft Inc. for Mule Runtime Enterprise Edition
Launching a JVM...
Running Mule on testing mode
Starting the Mule Container...
WrapperManager: Initializing...
INFO 2018-08-20 14:07:44,466 [WrapperListener_start_runner] org.mule.runtime.module.launcher.MuleContainer:
**********************************************************************
* Server started: 8/20/18 2:07 PM *
* JDK: 1.8.0_152 (mixed mode) *
* JDK properties: *
* - java.vendor = Oracle Corporation *
* - java.vm.name = Java HotSpot(TM) 64-Bit Server VM *
* - java.home = C:\Program Files\Java\jdk1.8.0_152\jre *
* OS: Windows 10 - (10.0, amd64) *
* Host: HYDWKW532 (172.16.170.82) *
* Mule services: *
* - api-gateway-contract-service-1.0.1-mule-service.jar *
* - mule-service-http-ee-1.1.3-mule-service.jar *
* - mule-service-oauth-1.1.2-mule-service.jar *
* - mule-service-scheduler-1.1.6-mule-service.jar *
* - mule-service-soap-1.1.6-mule-service.jar *
* - mule-service-weave-ee-2.1.4-mule-service.jar *
* Mule server plugins: *
* - mule-agent-plugin *
* - mule-debugger-mule-server-plugin *
* Applied patches: *
* Mule system properties: *
* - mule.testingMode = *
* - mule.base = *
* E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.e *
* e_7.2.1.201808031757\mule *
* - mule.home = *
* E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.e *
* e_7.2.1.201808031757\mule *
* - mule.forceConsoleLog = *
**********************************************************************
INFO 2018-08-20 14:08:06,124 [WrapperListener_start_runner] org.quartz.core.QuartzScheduler: Quartz Scheduler v.2.2.3 created.
INFO 2018-08-20 14:08:06,124 [WrapperListener_start_runner] org.quartz.simpl.RAMJobStore: RAMJobStore initialized.
INFO 2018-08-20 14:08:06,125 [WrapperListener_start_runner] org.quartz.core.QuartzScheduler: Scheduler meta-data: Quartz Scheduler (v2.2.3) '[MuleRuntime].' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 1 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
INFO 2018-08-20 14:08:06,125 [WrapperListener_start_runner] org.quartz.impl.StdSchedulerFactory: Quartz scheduler version: 2.2.3
INFO 2018-08-20 14:08:06,125 [WrapperListener_start_runner] org.quartz.core.QuartzScheduler: Scheduler [MuleRuntime]._$_NON_CLUSTERED started.
INFO 2018-08-20 14:08:06,174 [WrapperListener_start_runner] org.mule.runtime.module.service.internal.manager.MuleServiceManager:
**********************************************************************
* Started DefaultSchedulerService *
* *
* Resolved configuration values: *
* *
* gracefulShutdownTimeout: 15000 ms *
* cpuLight.threadPool.size: 8 *
* cpuLight.workQueue.size: 0 *
* io.threadPool.maxSize: 148 *
* io.threadPool.threadKeepAlive: 30000 ms *
* cpuIntensive.threadPool.size: 8 *
* cpuIntensive.workQueue.size: 1024 *
* *
* These can be modified by editing 'conf/scheduler-pools.conf' *
**********************************************************************
INFO 2018-08-20 14:08:06,483 [WrapperListener_start_runner] org.mule.runtime.module.launcher.coreextension.DefaultMuleCoreExtensionManagerServer: Initializing core extensions
INFO 2018-08-20 14:08:06,519 [WrapperListener_start_runner] com.mulesoft.mule.runtime.module.cluster.internal.config.ClusterTicketFileLoader: E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\.mule\mule-cluster.properties (The system cannot find the file specified)
WARN 2018-08-20 14:08:06,519 [WrapperListener_start_runner] com.mulesoft.mule.runtime.module.cluster.internal.HazelcastClusterCoreExtension: No cluster ID was specified -- High Availability will be disabled:
INFO 2018-08-20 14:08:06,520 [WrapperListener_start_runner] org.mule.runtime.module.launcher.coreextension.DefaultMuleCoreExtensionManagerServer: Core extension 'com.mulesoft.mule.runtime.module.cluster.internal.HazelcastClusterCoreExtension@3c04c922' initialized
INFO 2018-08-20 14:08:06,534 [WrapperListener_start_runner] com.mulesoft.mule.runtime.plugin.factory.ServerPluginDescriptorFactory: Creating plugin from folder E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\server-plugins\mule-agent-plugin
INFO 2018-08- INFO 2018-08-20 14:08:06,594 [WrapperListener_start_runner] com.mulesoft.agent.AgentPlugin: Mule agent keystore file does not exits in E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\conf\mule-agent.jks.
INFO 2018-08-20 14:08:06,656 [WrapperListener_start_runner] com.mulesoft.agent.AgentPlugin: Starting Mule Agent Version: null ; null
INFO 2018-08-20 14:08:09,320 [WrapperListener_start_runner] com.mulesoft.mule.runtime.plugin.manager.MulePluginManager: Registering plugin: mule-agent-plugin
INFO 2018-08-20 14:08:09,326 [WrapperListener_start_runner] com.mulesoft.mule.runtime.plugin.manager.MulePluginManager: Registering plugin: mule-debugger-server-plugin
INFO 2018-08-20 14:08:09,376 [WrapperListener_start_runner] org.mule.runtime.module.launcher.coreextension.DefaultMuleCoreExtensionManagerServer: Core extension 'com.mulesoft.mule.runtime.plugin.ServerPluginCoreExtension@29cdb898' initialized
INFO 2018-08-20 14:08:09,471 [WrapperListener_start_runner] org.mule.runtime.module.launcher.coreextension.DefaultMuleCoreExtensionManagerServer: Core extension 'com.mulesoft.mule.runtime.gw.deployment.ApiDeploymentCoreExtension@38ef7f42' initialized
INFO 2018-08-20 14:08:10,066 [WrapperListener_start_runner] org.mule.runtime.module.launcher.coreextension.DefaultMuleCoreExtensionManagerServer: Core extension 'com.mulesoft.mule.runtime.gw.analytics.AnalyticsCoreExtension@5dffc24b' initialized
INFO 2018-08-20 14:08:10,066 [WrapperListener_start_runner] org.mule.runtime.module.launcher.coreextension.DefaultMuleCoreExtensionManagerServer: Starting core extensions
INFO 2018-08-20 14:08:10,066 [WrapperListener_start_runner] org.mule.runtime.module.launcher.coreextension.DefaultMuleCoreExtensionManagerServer: Core extension 'com.mulesoft.mule.runtime.module.cluster.internal.HazelcastClusterCoreExtension@3c04c922' started
INFO 2018-08-20 14:08:10,066 [WrapperListener_start_runner] com.mulesoft.mule.runtime.plugin.manager.MulePluginManager: Starting plugin: mule-agent-plugin
INFO 2018-08-20 14:08:10,076 [WrapperListener_start_runner] com.mulesoft.agent.util.DefaultLicenseService: Mule EE evaluation version. Enabling Mule Agent usage.
INFO 2018-08-20 14:08:10,077 [WrapperListener_start_runner] com.mulesoft.agent.AgentTransportManager: Initializing transport: RestAgentTransport
INFO 2018-08-20 14:08:10,103 [WrapperListener_start_runner] org.eclipse.jetty.util.log: Logging initialized @27500ms to org.eclipse.jetty.util.log.Slf4jLog
WARN 2018-08-20 14:08:10,111 [WrapperListener_start_runner] com.mulesoft.agent.rest.AgentRestLayer: REST Agent transport is starting with no security
INFO 2018-08-20 14:08:10,232 [WrapperListener_start_runner] com.mulesoft.agent.AgentTransportManager: RestAgentTransport initialised
INFO 2018-08-20 14:08:10,233 [WrapperListener_start_runner] com.mulesoft.agent.AgentTransportManager: Skipping initialization of transport WebSocketAgentTransport
INFO 2018-08-20 14:08:10,485 [WrapperListener_start_runner] org.eclipse.jetty.server.Server: jetty-9.4.11.v20180605; built: 2018-06-05T18:24:03.829Z; git: d5fc0523cfa96bfebfbda19606cad384d772f04c; jvm 1.8.0_152-b16
INFO 2018-08-20 14:08:10,588 [WrapperListener_start_runner] org.eclipse.jetty.webapp.StandardDescriptorProcessor: NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet
INFO 2018-08-20 14:08:10,595 [WrapperListener_start_runner] org.eclipse.jetty.server.session: DefaultSessionIdManager workerName=node0
INFO 2018-08-20 14:08:10,595 [WrapperListener_start_runner] org.eclipse.jetty.server.session: No SessionScavenger set, using defaults
INFO 2018-08-20 14:08:10,597 [WrapperListener_start_runner] org.eclipse.jetty.server.session: node0 Scavenging every 660000ms
INFO 2018-08-20 14:08:11,168 [WrapperListener_start_runner] org.eclipse.jetty.server.handler.ContextHandler: Started o.e.j.w.WebAppContext@595b55a3{/,file:///E:/Personal/AnypointStudio/plugins/org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757/mule/bin/,AVAILABLE}
INFO 2018-08-20 14:08:11,168 [WrapperListener_start_runner] org.eclipse.jetty.server.Server: Started @28568ms
INFO 2018-08-20 14:08:11,176 [WrapperListener_start_runner] com.mulesoft.agent.AgentTransportManager: RestAgentTransport started
INFO 2018-08-20 14:08:11,227 [WrapperListener_start_runner] com.mulesoft.agent.services.AgentStudioManagementService: Starting Studio Management Service
INFO 2018-08-20 14:08:11,228 [WrapperListener_start_runner] com.mulesoft.agent.services.AgentStudioManagementService: Studio Checker is running
INFO 2018-08-20 14:08:11,230 [WrapperListener_start_runner] org.mule.runtime.module.launcher.coreextension.DefaultMuleCoreExtensionManagerServer: Core extension 'com.mulesoft.mule.runtime.plugin.ServerPluginCoreExtension@29cdb898' started
INFO 2018-08-20 14:08:11,231 [WrapperListener_start_runner] org.mule.runtime.module.launcher.coreextension.DefaultMuleCoreExtensionManagerServer: Core extension 'com.mulesoft.mule.runtime.gw.deployment.ApiDeploymentCoreExtension@38ef7f42' started
INFO 2018-08-20 14:08:11,231 [WrapperListener_start_runner] org.mule.runtime.module.launcher.coreextension.DefaultMuleCoreExtensionManagerServer: Core extension 'com.mulesoft.mule.runtime.gw.analytics.AnalyticsCoreExtension@5dffc24b' started
INFO 2018-08-20 14:08:11,239 [ServoPollScheduler-0] com.mulesoft.agent.configuration.postconfigure.DefaultPostConfigureRunner: Skipping the initialization of the mule.agent.nagios.jmx.internal.handler Internal Handler because it's disabled.
INFO 2018-08-20 14:08:11,321 [WrapperListener_start_runner] org.mule.runtime.module.deployment.internal.DefaultArchiveDeployer: ================== New Exploded Artifact: default
INFO 2018-08-20 14:08:11,405 [WrapperListener_start_runner] com.mulesoft.agent.configuration.postconfigure.DefaultPostConfigureRunner: Initializing the domain.deployment.notification.internal.message.handler ...
INFO 2018-08-20 14:08:11,405 [WrapperListener_start_runner] com.mulesoft.agent.configuration.postconfigure.DefaultPostConfigureRunner: domain.deployment.notification.internal.message.handler initialized successfully.
INFO 2018-08-20 14:08:11,432 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.deployment.impl.internal.domain.DefaultMuleDomain:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ New domain 'default' +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO 2018-08-20 14:08:11,432 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.deployment.impl.internal.domain.DefaultMuleDomain:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Initializing domain 'default' +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO 2018-08-20 14:08:11,810 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.extension.internal.manager.DefaultExtensionManager: Registering extension ee (version: 4.1.3 vendor: MuleSoft, Inc. )
INFO 2018-08-20 14:08:11,822 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.extension.internal.manager.DefaultExtensionManager: Registering extension mule (version: 4.1.3 vendor: MuleSoft, Inc. )
INFO 2018-08-20 14:08:12,118 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.privileged.lifecycle.AbstractLifecycleManager: Initialising RegistryBroker
INFO 2018-08-20 14:08:12,119 [WrapperListener_start_runner] [event: ] org.mule.runtime.config.internal.MuleArtifactContext: Refreshing org.mule.runtime.config.internal.MuleArtifactContext: default (DOMAIN)
INFO 2018-08-20 14:08:12,235 [WrapperListener_start_runner] [event: ] org.mule.runtime.config.internal.processor.MuleInjectorProcessor: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO 2018-08-20 14:08:12,237 [WrapperListener_start_runner] [event: ] org.mule.runtime.config.internal.ObjectProviderAwareBeanFactory: Overriding bean definition for bean '_muleConfiguration' with a different definition: replacing [Generic bean: class [org.mule.runtime.core.api.config.DefaultMuleConfiguration]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.mule.runtime.config.internal.MuleConfigurationConfigurator]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
INFO 2018-08-20 14:08:12,833 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.util.journal.TransactionJournal: Using files for tx logs E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\.\.mule\default\queue-tx-log\tx1.log and E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\.\.mule\default\queue-tx-log\tx2.log
INFO 2018-08-20 14:08:12,839 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.util.journal.TransactionJournal: Using files for tx logs E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\.\.mule\default\queue-xa-tx-log\tx1.log and E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\.\.mule\default\queue-xa-tx-log\tx2.log
INFO 2018-08-20 14:08:16,360 [WrapperListener_start_runner] [event: ] org.mule.runtime.api.el.AbstractBindingContextBuilderFactory: Loaded BindingContextBuilderFactory implementation 'org.mule.runtime.core.api.el.DefaultBindingContextBuilderFactory' from classloader 'org.mule.runtime.module.reboot.internal.MuleContainerSystemClassLoader@b799ae7'
INFO 2018-08-20 14:08:16,450 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.util.queue.QueueXaResourceManager: Starting ResourceManager
INFO 2018-08-20 14:08:16,450 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.util.queue.QueueXaResourceManager: Started ResourceManager
INFO 2018-08-20 14:08:16,467 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.context.DefaultMuleContext:
**********************************************************************
* Domain: default *
* OS encoding: windows-1252, Mule encoding: UTF-8 *
* *
**********************************************************************
INFO 2018-08-20 14:08:16,469 [WrapperListener_start_runner] org.mule.runtime.module.deployment.impl.internal.domain.DefaultMuleDomain:
**********************************************************************
* Started domain 'default' *
**********************************************************************
INFO 2018-08-20 14:08:16,472 [WrapperListener_start_runner] org.mule.runtime.module.deployment.internal.ArtifactArchiveInstaller: Exploding a Mule artifact archive: E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\apps\sample.jar
INFO 2018-08-20 14:08:17,458 [WrapperListener_start_runner] com.mulesoft.agent.configuration.postconfigure.DefaultPostConfigureRunner: Initializing the application.deployment.notification.internal.message.handler ...
INFO 2018-08-20 14:08:17,459 [WrapperListener_start_runner] com.mulesoft.agent.configuration.postconfigure.DefaultPostConfigureRunner: application.deployment.notification.internal.message.handler initialized successfully.
INFO 2018-08-20 14:08:17,480 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.deployment.impl.internal.application.DefaultMuleApplication:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ New app 'sample' +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO 2018-08-20 14:08:17,480 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.deployment.impl.internal.application.DefaultMuleApplication:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Initializing app 'sample' +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO 2018-08-20 14:08:21,307 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.extension.internal.manager.DefaultExtensionManager: Registering extension ee (version: 4.1.3 vendor: MuleSoft, Inc. )
INFO 2018-08-20 14:08:21,309 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.extension.internal.manager.DefaultExtensionManager: Registering extension mule (version: 4.1.3 vendor: MuleSoft, Inc. )
INFO 2018-08-20 14:08:22,080 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.extension.internal.manager.DefaultExtensionManager: Registering extension Sockets (version: 1.1.1 vendor: Mulesoft )
INFO 2018-08-20 14:08:22,082 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.extension.internal.manager.DefaultExtensionManager: Registering extension HTTP (version: 1.3.1 vendor: Mulesoft )
INFO 2018-08-20 14:08:22,088 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.extension.internal.manager.DefaultExtensionManager: Registering extension File (version: 1.1.3 vendor: Mulesoft )
INFO 2018-08-20 14:08:22,818 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.privileged.lifecycle.AbstractLifecycleManager: Initialising RegistryBroker
INFO 2018-08-20 14:08:22,818 [WrapperListener_start_runner] [event: ] org.mule.runtime.config.internal.MuleArtifactContext: Refreshing org.mule.runtime.config.internal.MuleArtifactContext: sample (APP)
INFO 2018-08-20 14:08:22,871 [WrapperListener_start_runner] [event: ] org.mule.runtime.config.internal.processor.MuleInjectorProcessor: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO 2018-08-20 14:08:22,873 [WrapperListener_start_runner] [event: ] org.mule.runtime.config.internal.ObjectProviderAwareBeanFactory: Overriding bean definition for bean '_muleConfiguration' with a different definition: replacing [Generic bean: class [org.mule.runtime.core.api.config.DefaultMuleConfiguration]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.mule.runtime.config.internal.MuleConfigurationConfigurator]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
INFO 2018-08-20 14:08:23,144 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.util.journal.TransactionJournal: Using files for tx logs E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\.\.mule\sample\queue-tx-log\tx1.log and E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\.\.mule\sample\queue-tx-log\tx2.log
INFO 2018-08-20 14:08:23,144 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.util.journal.TransactionJournal: Using files for tx logs E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\.\.mule\sample\queue-xa-tx-log\tx1.log and E:\Personal\AnypointStudio\plugins\org.mule.tooling.server.4.1.3.ee_7.2.1.201808031757\mule\.\.mule\sample\queue-xa-tx-log\tx2.log
INFO 2018-08-20 14:08:23,154 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.construct.FlowConstructLifecycleManager: Initialising flow: sampleFlow
INFO 2018-08-20 14:08:23,214 [WrapperListener_start_runner] [event: ] org.mule.runtime.api.message.AbstractMuleMessageBuilderFactory: Loaded MuleMessageBuilderFactory implementation 'org.mule.runtime.core.internal.message.DefaultMessageBuilderFactory' from classloader 'org.mule.runtime.module.reboot.internal.MuleContainerSystemClassLoader@b799ae7'
WARN 2018-08-20 14:08:23,307 [WrapperListener_start_runner] com.mulesoft.mule.runtime.gw.client.provider.ApiPlatformClientProvider: Client ID or Client Secret were not provided. API Platform client is DISABLED.
INFO 2018-08-20 14:08:23,317 [WrapperListener_start_runner] [event: ] org.mule.runtime.module.deployment.impl.internal.application.DefaultMuleApplication:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Starting app 'sample' +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO 2018-08-20 14:08:23,317 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.util.queue.QueueXaResourceManager: Starting ResourceManager
INFO 2018-08-20 14:08:23,317 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.util.queue.QueueXaResourceManager: Started ResourceManager
INFO 2018-08-20 14:08:23,323 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.construct.FlowConstructLifecycleManager: Starting flow: sampleFlow
INFO 2018-08-20 14:08:23,527 [WrapperListener_start_runner] [event: ] com.mulesoft.agent.configuration.postconfigure.DefaultPostConfigureRunner: Initializing the flow.status.notification.internal.message.handler ...
INFO 2018-08-20 14:08:23,527 [WrapperListener_start_runner] [event: ] com.mulesoft.agent.configuration.postconfigure.DefaultPostConfigureRunner: flow.status.notification.internal.message.handler initialized successfully.
INFO 2018-08-20 14:08:23,530 [WrapperListener_start_runner] [event: ] org.mule.runtime.core.internal.context.DefaultMuleContext:
**********************************************************************
* Application: sample *
* OS encoding: windows-1252, Mule encoding: UTF-8 *
* *
**********************************************************************
INFO 2018-08-20 14:08:23,532 [WrapperListener_start_runner] org.mule.runtime.module.deployment.impl.internal.application.DefaultMuleApplication:
**********************************************************************
* Started app 'sample' *
* Application plugins: *
* - File Common Plugin *
* (mule-module-file-extension-common-1.1.1-mule-plugin) *
* - Sockets (mule-sockets-connector-1.1.1-mule-plugin) *
* - File (mule-file-connector-1.1.3-mule-plugin) *
* - HTTP (mule-http-connector-1.3.1-mule-plugin) *
**********************************************************************
INFO 2018-08-20 14:08:23,537 [WrapperListener_start_runner] com.mulesoft.agent.configuration.postconfigure.DefaultPostConfigureRunner: Initializing the scheduling.notification.internal.message.handler ...
INFO 2018-08-20 14:08:23,537 [WrapperListener_start_runner] com.mulesoft.agent.configuration.postconfigure.DefaultPostConfigureRunner: scheduling.notification.internal.message.handler initialized successfully.
INFO 2018-08-20 14:08:23,540 [WrapperListener_start_runner] org.mule.runtime.module.deployment.internal.DeploymentDirectoryWatcher:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Mule is up and kicking (every 5000ms) +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO 2018-08-20 14:08:23,562 [WrapperListener_start_runner] org.eclipse.jetty.server.AbstractConnector: Started ServerConnector@4f790076{HTTP/1.1,[http/1.1]}{0.0.0.0:52057}
INFO 2018-08-20 14:08:23,563 [WrapperListener_start_runner] org.mule.runtime.module.deployment.internal.StartupSummaryDeploymentListener:
**********************************************************************
* - - + DOMAIN + - - * - - + STATUS + - - *
**********************************************************************
* default * DEPLOYED *
**********************************************************************
*******************************************************************************************************
* - - + APPLICATION + - - * - - + DOMAIN + - - * - - + STATUS + - - *
*******************************************************************************************************
* sample * default * DEPLOYED *
*******************************************************************************************************
</code></pre>
<p>Any help is appreciated.</p>
<p>Note: I am using Latest AnyPoint Studio.Version: 7.2.1 (java 8)
Note: The youtube video is 2 years older so might be a older Mule Version.</p>
| 3 | 10,871 |
Make this code run for several excel files
|
<p>So I want to run this script for several excel files, so instead of df3, I will import several excel files, and merge all the results into a dataframe.</p>
<p>Here is the main code example</p>
<pre><code>
import pandas as pd
d = {'City': ['Tokyo','Tokyo','Lisbon','Tokyo','Tokyo','Lisbon','Lisbon','Lisbon','Tokyo','Lisbon','Tokyo','Tokyo','Tokyo','Lisbon','Tokyo','Tokyo','Lisbon','Lisbon','Lisbon','Tokyo','Lisbon','Tokyo'],
'Card': ['Visa','Visa','Master Card','Master Card','Visa','Master Card','Visa','Visa','Master Card','Visa','Master Card','Visa','Visa','Master Card','Master Card','Visa','Master Card','Visa','Visa','Master Card','Visa','Master Card'],
'Colateral':['Yes','No','Yes','No','No','No','No','Yes','Yes','No','Yes','Yes','No','Yes','No','No','No','Yes','Yes','No','No','No'],
'Client Number':[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22],
'DebtPaid':[0.8,0.1,0.5,0.30,0,0.2,0.4,1,0.60,1,0.5,0.2,0,0.3,0,0,0.2,0,0.1,0.70,0.5,0.1]}
df = pd.DataFrame(data=d)
df2=df.groupby(['City','Card','Colateral'])['DebtPaid'].\
value_counts(bins=[-0.001,0,0.25,0.5,0.75,1,1.001,2],normalize=True)
d = {'City': ['Tokyo','Tokyo','Lisbon','Tokyo','Tokyo','Lisbon','Lisbon','Lisbon','Tokyo','Lisbon','Tokyo','Tokyo','Tokyo','Lisbon','Tokyo','Tokyo','Lisbon','Lisbon','Lisbon','Tokyo','Lisbon','Tokyo'],
'Card': ['Visa','Visa','Master Card','Master Card','Visa','Master Card','Visa','Visa','Master Card','Visa','Master Card','Visa','Visa','Master Card','Master Card','Visa','Master Card','Visa','Visa','Master Card','Visa','Master Card'],
'Colateral':['Yes','No','Yes','No','No','No','No','Yes','Yes','No','Yes','Yes','No','Yes','No','No','No','Yes','Yes','No','No','No'],
'Client Number':[23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],
'Total Debt':[100,240,200,1000,50,20,345,10,600,40,50,20,100,30,100,600,200,200,150,700,50,120]}
df3 = pd.DataFrame(data=d)
#First merge dataframes
df_out = df2.rename('Prob').reset_index().merge(df3, on=['City', 'Card', 'Colateral'])
#Use the right and left attributes of pd.Interval
df_out['lower'] = [x.left for x in df_out['DebtPaid']]
df_out['upper'] = [x.right for x in df_out['DebtPaid']]
#Calculate lower and upper partial prices
df_out['l_partial'] = df_out[['lower', 'Prob', 'Total Debt']].prod(axis=1)
df_out['u_partial'] = df_out[['upper', 'Prob', 'Total Debt']].prod(axis=1)
#Sum partial prices to get lower and upper price grouped on Client Number
final = df_out.groupby('Client Number')[['l_partial', 'u_partial']]\
.agg(lower_price=('l_partial', 'sum'),
upper_price=('u_partial', 'sum')).clip(0,np.inf)
w = (final['upper_price'].sum() + final['lower_price'].sum()) / 2
y = 1000
z = ((w/y)-1)*100
d1 = {'1': [w,y,z],
'Index':['Estimate','Real','Error']}
results = pd.DataFrame(data=d1).set_index('Index')
print(results)
</code></pre>
<p>This is what I tried to do in order to run the script with several excel files without sucess:</p>
<pre><code>files = [1,2,3,4,5]
for x in files:
df3 = pd.read_excel(str(x) + '.xlsx')
#First merge dataframes
df_out = df2.rename('Prob').reset_index().merge(df3, on=['City', 'Card', 'Colateral'])
#Use the right and left attributes of pd.Interval
df_out['lower'] = [x.left for x in df_out['DebtPaid']]
df_out['upper'] = [x.right for x in df_out['DebtPaid']]
#Calculate lower and upper partial prices
df_out['l_partial'] = df_out[['lower', 'Prob', 'Total Debt']].prod(axis=1)
df_out['u_partial'] = df_out[['upper', 'Prob', 'Total Debt']].prod(axis=1)
#Sum partial prices to get lower and upper price grouped on Client Number
final = df_out.groupby('Client Number')[['l_partial', 'u_partial']]\
.agg(lower_price=('l_partial', 'sum'),
upper_price=('u_partial', 'sum')).clip(0,np.inf)
w = (final['upper_price'].sum() + final['lower_price'].sum()) / 2
y = 1000
z = ((w/y)-1)*100
d1 = {x : [w,y,z],
'Index':['Estimate','Real','Error']}
results = pd.DataFrame(data=d1).set_index('Index')
results
</code></pre>
<p><a href="https://i.stack.imgur.com/19pZv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/19pZv.png" alt="enter image description here" /></a></p>
<p>It only shows results for one excel file. Do you know how I can solve this?</p>
| 3 | 1,853 |
Android error String can't be converted to JSONArray
|
<p>This is my main activity. I cannot login as it says java.lang.String cannot be converted to JSONArray. What could be the error? I cannot resolve it.</p>
<p>This is my main activity.java :</p>
<pre><code>ppublic class MainActivity extends AppCompatActivity {
private EditText email, password;
private Button btn_login;
private ProgressBar loading;
private static String URL_LOGIN ="http://itsolutionsnepal.com/attendance/api/employeeLogin";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading= findViewById(R.id.loading);
email = findViewById(R.id.editTextUserEmail);
password = findViewById(R.id.editTextPassword);
btn_login = findViewById(R.id.buttonRegister);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mEmail = email.getText().toString().trim();
String mPassword = password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPassword.isEmpty()) {
Login(mEmail, mPassword);
}else{
email.setError("Please Enter Email");
password.setError("Please Enter Password");
}
}
});
}
private void Login(final String email, final String password) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST,URL_LOGIN,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("_first_name").trim();
String email = object.getString("_email").trim();
// JSONObject jsnobject = new JSONObject(response);
// JSONArray jsonArray = jsnobject.getJSONArray("");
//JSONObject object = jsonArray.getJSONObject(i);
// JSONObject jsonResponse = new JSONObject(response);
//
// JSONArray jsonArray = jsonResponse.getJSONArray("");
//JSONObject jsonObject = new JSONObject(response);
// Log.d("JSON", jsonObject.toString());
//String success = jsonObject.getString("");
// JSONArray jsonArray = jsonObject.getJSONArray("");
// JSONArray jsonArray = new JSONArray(response);
// JSONObject jsonObject = new JSONObject("");
// String code = jsonObject.getString("");
// if (success.equals("1"))
// {
// String name =
object.getString("_first_name").trim();
// String email =
object.getString("_email").trim();
// Toast.makeText(MainActivity.this,
"Success
Login \nYour name: "+name+"\nYour Email: "+email,
// Toast.LENGTH_LONG).show();
System.out.println("Value of response - " +
response);
System.out.println("First Name : " + name);
System.out.println("Email : " + email);
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
intent.putExtra("name",name);
intent.putExtra("email", email);
startActivity(intent);
loading.setVisibility(View.GONE);
//}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Error" +e.toString(),
Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error" +error.toString(),
Toast.LENGTH_LONG).show();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("_email", email);
params.put("_password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
</code></pre>
<p>And this is my json response:</p>
<p><a href="https://i.stack.imgur.com/BVlM9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BVlM9.png" alt="enter image description here"></a></p>
<p>Log cat:</p>
<p><a href="https://i.stack.imgur.com/LjQG9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LjQG9.png" alt="enter image description here"></a></p>
<p>Log cat:</p>
<p><a href="https://i.stack.imgur.com/eDAOI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eDAOI.png" alt="enter image description here"></a></p>
| 3 | 2,962 |
C# display specific item in listview
|
<p>I'm doing an assignment involve searching in a listview. I have a textbox and a listview that bind to a list<>. And I want to display the item in the listview which is similar to what I type in the textbox, or at least scroll to it. Here is my code:
XAML code:</p>
<pre><code><Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MathDictionary"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ViewModel="using:MathDictionary.ViewModel"
x:Class="MathDictionary.MainPage"
mc:Ignorable="d">
<Page.DataContext>
<ViewModel:MainViewModel/>
</Page.DataContext>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"></ColumnDefinition>
<ColumnDefinition Width="auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="150"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Width="200" HorizontalAlignment="Left" Grid.Row="1">
<TextBox x:Name="SearchT" TextChanged="SearchT_TextChanged_1"></TextBox>
<ListView x:Name="ListWord" ItemsSource="{Binding Data.Words}" SelectionChanged="ListWord_SelectionChanged" >
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding words}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
<StackPanel Grid.Column="1" Grid.Row="1" Margin="40,0,0,0">
<TextBlock x:Name="KeyT" FontSize="30" ></TextBlock>
<TextBlock x:Name="ValueT" FontSize="20" ></TextBlock>
</StackPanel>
</Grid>
</Grid>
</code></pre>
<p>
And the code I want to call when typing:</p>
<pre><code>private void SearchT_TextChanged_1(object sender, TextChangedEventArgs e)
{
if (SearchT.Text != "")
{
for (int i = ListWord.Items.Count - 1; i >= 0; i--)
{
var item = ListWord.Items[i];
if (item.ToString().Contains(SearchT.Text.ToString()))
{
//Display the item or scroll to it
}
else
{
//Do something here
}
}
}
}
</code></pre>
| 3 | 1,495 |
Why does Rust's documentation for methods use a separate builder struct as an example?
|
<p>I was going through the <a href="https://doc.rust-lang.org/book/method-syntax.html" rel="nofollow">struct and method docs</a> and was wondering why the docs use this example:</p>
<pre><code>struct Circle {
x: f64,
y: f64,
radius: f64,
}
impl Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
struct CircleBuilder {
x: f64,
y: f64,
radius: f64,
}
impl CircleBuilder {
fn new() -> CircleBuilder {
CircleBuilder { x: 0.0, y: 0.0, radius: 1.0, }
}
fn x(&mut self, coordinate: f64) -> &mut CircleBuilder {
self.x = coordinate;
self
}
fn y(&mut self, coordinate: f64) -> &mut CircleBuilder {
self.y = coordinate;
self
}
fn radius(&mut self, radius: f64) -> &mut CircleBuilder {
self.radius = radius;
self
}
fn finalize(&self) -> Circle {
Circle { x: self.x, y: self.y, radius: self.radius }
}
}
fn main() {
let c = CircleBuilder::new()
.x(1.0)
.y(2.0)
.radius(2.0)
.finalize();
println!("area: {}", c.area());
println!("x: {}", c.x);
println!("y: {}", c.y);
}
</code></pre>
<p>My slightly modified code is smaller and appears to do the exact same thing:</p>
<pre><code>struct Circle {
x: f64,
y: f64,
radius: f64,
}
impl Circle {
fn new() -> Circle {
Circle { x: 0.0, y: 0.0, radius: 1.0, }
}
fn x(&mut self, coordinate: f64) -> &mut Circle {
self.x = coordinate;
self
}
fn y(&mut self, coordinate: f64) -> &mut Circle {
self.y = coordinate;
self
}
fn radius(&mut self, radius: f64) -> &mut Circle {
self.radius = radius;
self
}
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
fn finalize(&self) -> Circle {
Circle { x: self.x, y: self.y, radius: self.radius }
}
}
fn main() {
let c = Circle::new()
.x(1.0)
.y(2.0)
.radius(2.0)
.finalize();
println!("area: {}", c.area());
println!("x: {}", c.x);
println!("y: {}", c.y);
}
</code></pre>
| 3 | 1,149 |
AVCaptureDevice Low Light Boost Does Not work
|
<p>The low light boost property of AVCaptureDevice is not enabling when it should. I am testing this on an iPhone 5 with iOS 6. Here's the code:</p>
<pre><code> // finds a device that supports the video media type
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSArray *allDevices = [AVCaptureDevice devices];
for (AVCaptureDevice *currentDevice in allDevices) {
if (currentDevice.position == AVCaptureDevicePositionBack) {
device = currentDevice;
}
}
NSError *deviceError = nil;
if (device.isFlashAvailable){
[device lockForConfiguration:&deviceError];
device.flashMode = AVCaptureFlashModeAuto;
[device unlockForConfiguration];
}
if ([device respondsToSelector:@selector(isLowLightBoostSupported)]) {
if ([device lockForConfiguration:nil]) {
if (device.isLowLightBoostSupported)
device.automaticallyEnablesLowLightBoostWhenAvailable = YES;
[device unlockForConfiguration];
}
}
if ([device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
[device lockForConfiguration:&deviceError];
device.exposureMode = AVCaptureExposureModeContinuousAutoExposure;
// CODE FOR device.exposurePointOfInterest determined from wherever the face is based off of the faceScan method
[device unlockForConfiguration];
}
AVCaptureDeviceInput *newVideoInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&deviceError];
AVCaptureStillImageOutput *newStillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
AVVideoCodecJPEG, AVVideoCodecKey,
nil];
[newStillImageOutput setOutputSettings:outputSettings];
self.sess = [[AVCaptureSession alloc] init];
if ([self.sess canAddInput:newVideoInput]) {
[self.sess addInput:newVideoInput];
}
if ([self.sess canAddOutput:newStillImageOutput]) {
[self.sess addOutput:newStillImageOutput];
}
self.stillImageOutput = newStillImageOutput;
if (device.lowLightBoostEnabled) {
NSLog(@"ENABLED");
}
// register as an observer of changes to lowLightBoostEnabled
[device addObserver:self forKeyPath:@"automaticallyEnablesLowLightBoostWhenAvailable" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:NULL];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqual:@"lowLightBoostEnabled"]) {
NSLog(@"lowLightBoostEnabled changed");
NSNumber *boostIsActiveValue = [change objectForKey:NSKeyValueChangeNewKey];
BOOL boostIsActive = boostIsActiveValue.boolValue;
NSLog(@"is low light boost currently active: %d", boostIsActive);
}
}
</code></pre>
<p>Can anyone give me any help? I've looked online but haven't found very conclusive results. I'd appreciate all the help I can get.</p>
| 3 | 1,126 |
How to use datalist input with Formik?
|
<p>I am trying to use datalist in a formik form with ReactJS. I am trying to show a list of array dynamically in datalist option in formik form. So, I have done as below:</p>
<pre><code><Formik
initialValues={initialValues}
validationSchema={AddEmployeeFormValidationSchema}
onSubmit={props.handleSubmitMethod}
>
{(formikProps) => (
<Form onSubmit={formikProps.handleSubmit}>
<div className="form-row">
<Col>
<FormGroup>
<label>Designation</label>
<Field
type="text"
name="designation"
list="designations"
id="designation"
>
<datalist id="designations">
{props.designations.map((designation) => {
return (
<option
value={`${designation.id}`}
key={`${designation.id}`}
>
{`${designation.designation_title}`}
</option>
);
})}
</datalist>
</Field>
<ErrorMessage
name="designation"
component="div"
className="text-danger"
/>
</FormGroup>
</Col>
<div className="form-row mt-3 text-right">
<Col>
<Button
className="primary-color"
type="submit"
disabled={!formikProps.dirty || formikProps.isSubmitting}
>
Submit
</Button>
</Col>
</div>
</Form>
)}
</Formik>
</code></pre>
<p>But it shows me the following error:</p>
<pre><code>Error: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.
</code></pre>
<p>Is it possible to use datalist with formik?</p>
| 3 | 1,115 |
How to use an Actor based source with an Akka Graph?
|
<p>I'm attempting to send data via an actor to a runnable graph that contains a fan out.</p>
<p>I define the source as :</p>
<pre><code>final Source<Integer, ActorRef> integerSource =
Source.actorRef(
elem -> {
if (elem == Done.done()) return Optional.of(CompletionStrategy.immediately());
else return Optional.empty();
},
elem -> Optional.empty(),
10,
OverflowStrategy.dropHead());
</code></pre>
<p>But I'm unsure how to get a handle on an <code>ActoRef</code> to send data via an actor to the source so that the runnable graph will process messages asynchronously as they are received :</p>
<pre><code>RunnableGraph<CompletionStage<Done>> graph = RunnableGraph.fromGraph(
GraphDSL.create(sink, (builder, out) -> {
SourceShape<Integer> sourceShape = builder.add(integerSource);
FlowShape<Integer, Integer> flow1Shape = builder.add(flow1);
FlowShape<Integer, Integer> flow2Shape = builder.add(flow1);
UniformFanOutShape<Integer, Integer> broadcast =
builder.add(Broadcast.create(2));
UniformFanInShape<Integer, Integer> merge =
builder.add(Merge.create(2));
builder.from(sourceShape)
.viaFanOut(broadcast)
.via(flow1Shape);
builder.from(broadcast).via(flow2Shape);
builder.from(flow1Shape)
.viaFanIn(merge)
.to(out);
builder.from(flow2Shape).viaFanIn(merge);
return ClosedShape.getInstance();
} )
);
</code></pre>
<p>Entire src :</p>
<pre><code>import akka.Done;
import akka.NotUsed;
import akka.actor.ActorRef;
import akka.actor.typed.ActorSystem;
import akka.actor.typed.javadsl.Behaviors;
import akka.stream.*;
import akka.stream.javadsl.*;
import lombok.extern.slf4j.Slf4j;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
@Slf4j
public class GraphActorSource {
private final static ActorSystem actorSystem = ActorSystem.create(Behaviors.empty(), "flowActorSystem");
public void runFlow() {
final Source<Integer, ActorRef> integerSource =
Source.actorRef(
elem -> {
if (elem == Done.done()) return Optional.of(CompletionStrategy.immediately());
else return Optional.empty();
},
elem -> Optional.empty(),
10,
OverflowStrategy.dropHead());
Flow<Integer, Integer, NotUsed> flow1 = Flow.of(Integer.class)
.map (x -> {
System.out.println("Flow 1 is processing " + x);
return (x * 2);
});
Sink<Integer, CompletionStage<Done>> sink = Sink.foreach(x -> {
System.out.println(x);
});
RunnableGraph<CompletionStage<Done>> graph = RunnableGraph.fromGraph(
GraphDSL.create(sink, (builder, out) -> {
SourceShape<Integer> sourceShape = builder.add(integerSource);
FlowShape<Integer, Integer> flow1Shape = builder.add(flow1);
FlowShape<Integer, Integer> flow2Shape = builder.add(flow1);
UniformFanOutShape<Integer, Integer> broadcast =
builder.add(Broadcast.create(2));
UniformFanInShape<Integer, Integer> merge =
builder.add(Merge.create(2));
builder.from(sourceShape)
.viaFanOut(broadcast)
.via(flow1Shape);
builder.from(broadcast).via(flow2Shape);
builder.from(flow1Shape)
.viaFanIn(merge)
.to(out);
builder.from(flow2Shape).viaFanIn(merge);
return ClosedShape.getInstance();
} )
);
graph.run(actorSystem);
}
public static void main(String args[]){
new GraphActorSource().runFlow();
}
}
</code></pre>
<p>How to send data to the Runnable graph via an actor?</p>
<p>Something like ? :</p>
<pre><code>integerSource.tell(1)
integerSource.tell(2)
integerSource.tell(3)
</code></pre>
| 3 | 2,312 |
ASP.NET: How to avoid situation that dynamically created button event refreshes the page instead of doing relevant code
|
<p>(<strong>Original text updated!</strong>)</p>
<p>I am slowly getting into ASP.NET, currently trying to make a small webforms app for a hackathon.</p>
<p>The page that I am having problems with is supposed to show a list of companies to which person can apply.</p>
<p>Since the list of those companies can change, company always can be added or removed, I want to make some kind of table which loads values dynamically. The table appears when a user clicks "View all companies", it shows a table with each row including the name of company and a button to move to the page of this company. At this stage, I am trying to make something even more simple, for the sake of testing.</p>
<p>So, the button should just display some kind of text.</p>
<p>But here's the problem.
When I click on the button, it just resets the page and as I understand, runs "Page_Load". The text is also resets to the value from Page_Load.</p>
<p>Now, I'll try to give code and try to give the best descriptions.</p>
<p>Here's the Page_Load, on first load it just displays the name of the user, and hides the table with company names. On non-first load, it should run click button events.</p>
<pre><code> protected void Page_Load(object sender, EventArgs e)
{
HRGlobalHub.Code.Start.Firebase.thisFirebaseClient = new FireSharp.FirebaseClient(HRGlobalHub.Code.Start.Firebase.thisFirebaseConfig);
pnlCompaniesView.Visible = false;
if (!IsPostBack)
{
if (thisUser == null)
lblWelcomeUser.Text = "Welcome";
else
lblWelcomeUser.Text = "Welcome, " + thisUser.FirstName + " " + thisUser.LastName;
gCompany = new Code.Company.Company();
}
else
{
if (Action=="Apply")
btnApplyClick(this, e);
else if (Action == "Suggest")
btnSuggestClick(this, e);
if (Action == "View")
btnViewClick(this, e);
}
}
</code></pre>
<p>The code for showing all companies comes here:</p>
<pre><code> protected async void btnViewAllCompanies_Click(object sender, EventArgs e)
{
ResetCompaniesTable();
lblWelcomeUser.Text = "ViewAll";
FirebaseResponse response = await HRGlobalHub.Code.Start.Firebase.thisFirebaseClient.GetTaskAsync("HRGlobalHub/Database/Companies/CompaniesList/");
HRGlobalHub.Code.Company.CompaniesNamesList thisData = response.ResultAs<HRGlobalHub.Code.Company.CompaniesNamesList>();
string[] CompanyArray = thisData.CompanyNameListVar.Split(',');
for (int i = 1; i < CompanyArray.Length; i++)
{
response = await HRGlobalHub.Code.Start.Firebase.thisFirebaseClient.GetTaskAsync("HRGlobalHub/Database/Companies/CompaniesDatabase/" + CompanyArray[i]);
HRGlobalHub.Code.Company.Company result = response.ResultAs<HRGlobalHub.Code.Company.Company>();
tbtTestTable.Rows.Add(NewCompanyRow(result));
}
pnlCompaniesView.Visible = true;
pnlCompaniesView.Width = 1100;
tbtTestTable.Width = 1100;
lblWelcomeUser.Text = tbtTestTable.Visible.ToString();
}
</code></pre>
<p>This part loads first just the names of companies, then full companies data from the server. Each company turns into a table row. It also creates OnClientClick button events, that should load on non-first Page Load.</p>
<pre><code> public TableRow NewCompanyRow(HRGlobalHub.Code.Company.Company thisCompany)
{
TableRow newRow = new TableRow();
Button btnApply = new Button();
btnApply.Text = "Apply";
btnApply.OnClientClick += gCompany = thisCompany;
btnApply.OnClientClick += Action = "Apply";
Button btnSuggest = new Button();
btnSuggest.Text = "Suggest";
btnSuggest.OnClientClick += gCompany = thisCompany;
btnSuggest.OnClientClick += Action = "Suggest";
Button btnView = new Button();
btnView.Text = "View";
btnView.OnClientClick += gCompany = thisCompany;
btnView.OnClientClick += Action = "View";
TableCell[] Cells = new TableCell[6];
for (int i = 0; i < Cells.Length; i++)
Cells[i] = new TableCell();
Cells[0].Text = thisCompany.Name;
Cells[1].Text = thisCompany.FieldOfWork;
Cells[2].Text = thisCompany.Employees.Count.ToString();
Cells[3].Controls.Add(btnView);
Cells[4].Controls.Add(btnApply);
Cells[5].Controls.Add(btnSuggest);
for (int i = 0; i < Cells.Length; i++)
Cells[i].Width = 150;
newRow.Width = 900;
for (int i = 0; i < Cells.Length; i++)
newRow.Cells.Add(Cells[i]);
btnApply.Width = 150;
btnSuggest.Width = 150;
btnView.Width = 150;
return newRow;
}
</code></pre>
<p>Again, since it's just testing stage for this page, the button should only display the name of the company that it gets as variable.</p>
<pre><code> void btnApplyClick(Object sender, EventArgs e, HRGlobalHub.Code.Company.Company thisCompany)
{
lblWelcomeUser.Text = "Apply to " + thisCompany.Name;
}
</code></pre>
<p>This works but only partly: whatever I try the code from Page Load always runs the last "mentioned" Action (which is "View") and always goes for the company from the last row.</p>
<p>Please help me solve this!</p>
<p>Evgenie</p>
| 3 | 2,308 |
Exception while dispatching incoming RPC call java.lang.NoSuchMethodError: com.google.gwt.user.server.rpc.RPCRequest
|
<p>I have GWT page with Hibernate and MySQL setup already. I'm running it in SuperDev mode and here is the error I get after compiling the page:</p>
<pre><code> [WARN] Exception while dispatching incoming RPC call
java.lang.NoSuchMethodError: com.google.gwt.user.server.rpc.RPCRequest.<init>(Ljava/lang/reflect/Method;[Ljava/lang/Object;Lcom/google/gwt/user/server/rpc/SerializationPolicy;)V
at com.google.gwt.user.server.rpc.RPCCopy_GWT15.decodeRequest(RPCCopy_GWT15.java:278)
at com.google.gwt.user.server.rpc.RPCCopy.decodeRequest(RPCCopy.java:136)
at net.sf.gilead.gwt.PersistentRemoteService.processCall(PersistentRemoteService.java:143)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:305)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:686)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:501)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:68)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:960)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1021)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:668)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Unknown Source)
[ERROR] 500 - POST /atlas_emergency_status_page/DBService (127.0.0.1) 57 bytes
Request headers
Host: 127.0.0.1:8888
Connection: keep-alive
Content-Length: 162
X-GWT-Module-Base: http://127.0.0.1:8888/atlas_emergency_status_page/
X-GWT-Permutation: BE75887428AD071A73976B7011B26FBF
Origin: http://127.0.0.1:8888
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Content-Type: text/x-gwt-rpc; charset=UTF-8
Accept: */*
Referer: http://127.0.0.1:8888/ATLAS_Emergency_Status_Page.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,fr-CH;q=0.6,fr;q=0.4,ka;q=0.2,ru;q=0.2
Response headers
Content-Type: text/plain
</code></pre>
<p>what might be causing this?</p>
<p><strong>Edit:</strong></p>
<p>Here is my <strong>web.xml</strong>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<!-- Servlets -->
<servlet>
<servlet-name>greetServlet</servlet-name>
<servlet-class>ch.cern.atlas.emergency.status.server.GreetingServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>greetServlet</servlet-name>
<url-pattern>/atlas_emergency_status_page/greet</url-pattern>
</servlet-mapping>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>ATLAS_Emergency_Status_Page.html</welcome-file>
</welcome-file-list>
<!-- Servlets -->
<servlet>
<servlet-name>LoginService</servlet-name>
<servlet-class>ch.cern.atlas.emergency.status.server.LoginServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginService</servlet-name>
<url-pattern>/atlas_emergency_status_page/LoginService</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DBService</servlet-name>
<servlet-class>ch.cern.atlas.emergency.status.server.DBServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DBService</servlet-name>
<url-pattern>/atlas_emergency_status_page/DBService</url-pattern>
</servlet-mapping>
</web-app>
</code></pre>
| 3 | 2,478 |
Kubernetes kube-dns Pause container in crashloop with Error adding network: failed to Statfs \"/proc/54226/ns/net\":
|
<p>I have a Kubernetes onebox deployment with the following (containerized) components, all running as <code>--net=host</code>, with kubelet running as a privileged Docker container with the kubernetes flag <code>--allow-privileged</code> set to true.</p>
<pre><code>gcr.io/google_containers/hyperkube-amd64:v1.7.9 "/bin/bash -c './hype" kubelet
gcr.io/google_containers/hyperkube-amd64:v1.7.9 "/bin/bash -c './hype" kube-proxy
gcr.io/google_containers/hyperkube-amd64:v1.7.9 "/bin/bash -c './hype" kube-scheduler
gcr.io/google_containers/hyperkube-amd64:v1.7.9 "/bin/bash -c './hype" kube-controller-manager
gcr.io/google_containers/hyperkube-amd64:v1.7.9 "/bin/bash -c './hype" kube-apiserver
quay.io/coreos/etcd:v3.1.0 "/usr/local/bin/etcd " etcd
</code></pre>
<p>On top of this, I enabled the addon manager with <code>kubectl create -f https://github.com/kubernetes/kubernetes/blob/master/test/kubemark/resources/manifests/kube-addon-manager.yaml</code>,
with the default yaml manifests for calico 2.6.1 and kube-dns 1.14.5 mounted to <code>/etc/kubernetes/addons/</code>. The calico pod comes up with two nodes (install-cni and calico-node) as expected. </p>
<p>However, kube-dns gets stuck in ContainerCreating or ContainerCannotRun, with the following error while trying to start the Kubernetes pause container: </p>
<pre><code>{"log":"I1111 00:35:19.549318 1 manager.go:913] Added container: \"/kubepods/burstable/pod3173eef3-c678-11e7-ac4b-e41d2d59689e/1dd57d6f6c996d7abe061f6236fc8a0150cf6f95d16d5c3c462c9ed7158d3c54\" (aliases: [k8s_POD_kube-dns-v20-141138543-pmdww_kube-system_3173eef3-c678-11e7-ac4b-e41d2d59689e_0 1dd57d6f6c996d7abe061f6236fc8a0150cf6f95d16d5c3c462c9ed7158d3c54], namespace: \"docker\")\n","stream":"stderr","time":"2017-11-11T00:35:19.5526284Z"}
{"log":"I1111 00:35:19.549433 1 cni.go:291] About to add CNI network cni-loopback (type=loopback)\n","stream":"stderr","time":"2017-11-11T00:35:19.5526748Z"}
{"log":"I1111 00:35:19.549504 1 handler.go:325] Added event \u0026{/kubepods/burstable/pod3173eef3-c678-11e7-ac4b-e41d2d59689e/1dd57d6f6c996d7abe061f6236fc8a0150cf6f95d16d5c3c462c9ed7158d3c54 2017-11-11 00:35:19.3931718 +0000 UTC containerCreation {\u003cnil\u003e}}\n","stream":"stderr","time":"2017-11-11T00:35:19.5527217Z"}
{"log":"I1111 00:35:19.551134 1 container.go:407] Start housekeeping for container \"/kubepods/burstable/pod3173eef3-c678-11e7-ac4b-e41d2d59689e/1dd57d6f6c996d7abe061f6236fc8a0150cf6f95d16d5c3c462c9ed7158d3c54\"\n","stream":"stderr","time":"2017-11-11T00:35:19.5527441Z"}
{"log":"E1111 00:35:19.555099 1 cni.go:294] Error adding network: failed to Statfs \"/proc/54226/ns/net\": no such file or directory\n","stream":"stderr","time":"2017-11-11T00:35:19.5553606Z"}
{"log":"E1111 00:35:19.555122 1 cni.go:237] Error while adding to cni lo network: failed to Statfs \"/proc/54226/ns/net\": no such file or directory\n","stream":"stderr","time":"2017-11-11T00:35:19.5553887Z"}
{"log":"I1111 00:35:19.600281 1 manager.go:970] Destroyed container: \"/kubepods/burstable/pod3173eef3-c678-11e7-ac4b-e41d2d59689e/1dd57d6f6c996d7abe061f6236fc8a0150cf6f95d16d5c3c462c9ed7158d3c54\" (aliases: [k8s_POD_kube-dns-v20-141138543-pmdww_kube-system_3173eef3-c678-11e7-ac4b-e41d2d59689e_0 1dd57d6f6c996d7abe061f6236fc8a0150cf6f95d16d5c3c462c9ed7158d3c54], namespace: \"docker\")\n","stream":"stderr","time":"2017-11-11T00:35:19.6005722Z"}
</code></pre>
<p>I see \pause containers keep coming up just to exit a second later, with an innocuous error message (this one is old, I stopped the cluster so it wouldn't keep spawning more containers):</p>
<pre><code>ubuntu@r172-16-6-39:~$ docker ps -a | grep 216e39defa36
216e39defa36 gcr.io/google_containers/pause-amd64:3.0 "/pause" About an hour ago Exited (0) About an hour ago k8s_POD_kube-dns-v20-141138543-xvdmv_kube-system_0594732f-c688-11e7-9da5-e41d2d59689e_17
ubuntu@r172-16-6-39:~$ docker logs 216e39defa36
shutting down, got signal: Terminated
</code></pre>
<p>The dir <code>/proc/54226</code> doesn't exist on my host, which I assume is why CNI is complaining. But the pause containers for Calico are fine, running the same image, so something must be either failing to write only in the case of kube-dns, or not trying to write in the case of Calico. I found some references to a similar <a href="https://bugzilla.redhat.com/show_bug.cgi?id=1414963" rel="nofollow noreferrer">SELinux-related error on Openshift</a>, but I'm running a bare Ubuntu 14.04 VM without SELinux even installed. </p>
<pre><code>ubuntu@r172-16-6-39:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.4 LTS
Release: 14.04
Codename: trusty
ubuntu@r172-16-6-39:~$ setenforce
The program 'setenforce' is currently not installed. You can install it by typing:
sudo apt-get install selinux-utils
</code></pre>
<p>My CNI conf is also pretty simple, generated by the install-cni calico container:</p>
<pre><code>ubuntu@r172-16-6-39:~$ cat /etc/cni/net.d/10-calico.conf
{
"name": "k8s-pod-network",
"cniVersion": "0.1.0",
"type": "calico",
"log_level": "debug",
"datastore_type": "kubernetes",
"nodename": "172.16.6.39",
"mtu": 1500,
"ipam": {
"type": "host-local",
"subnet": "usePodCidr"
},
"policy": {
"type": "k8s",
"k8s_auth_token": "****"
},
"kubernetes": {
"k8s_api_root": "https://168.16.0.1:443",
"kubeconfig": "/etc/kubernetes/kubeconfig"
}
}
</code></pre>
<p>Has anyone hit something similar?</p>
| 3 | 2,584 |
Iterate through deeply nested object to generate html optgroup/options
|
<p>I am trying to get the keys of my object and create an optgroup if it contains children and then make children options of the optgroup. If a child is also a object than i want to nest another optgroup within parent optgroup. Below is my object myTypes</p>
<pre><code>let myTypes = {
women:
{
tops:
{
poloshirts:"polo shirts",
tshirts: "t-shirts",
buttondown: "button down",
longsleeve:"long sleeve",
vneck:"vneck",
tanktop:"tanktop",
blouse:"blouse",
croptop:"croptop",
drifit: "dri-fit",
dressshirt:"dress shirt"
},
bottoms:
{
shorts:"shorts",
jeans:"jeans",
joggers:"joggers",
skirts:"skirts",
dresspants:"dresspants",
leggings:"leggings"
},
shoes:
{
boots:"boots",
sneakers: "sneakers",
sandals:"sandals",
flats:"flats",
heels:"heels"
},
jewelry:
{
rings: "rings",
bracelets:"bracelets",
necklaces: "necklaces",
anklets: "anklets"
},
sweaters: "sweaters",
sweatshirts: "sweatshirts",
hoodies: "hoodies",
dresses:
{
sundress: "sundress",
short: "short",
long: "long",
maxidress: "maxidress"
},
accessories:
{
watches:"watches",
glasses:
{
sunglasses: "sunglasses",
reading:"reading"
},
wallets: "wallets",
keychains: "keychains",
lanyards:"lanyards",
belts:"belts",
purses:"purses"
}
},
men:
{
tops:
{
poloshirts:"polo shirts",
tshirts: "t-shirts",
buttondown: "button down",
longsleeve:"long sleeve",
vneck:"vneck",
tanktop:"tanktop",
drifit: "dri-fit",
dressshirt: "dress shirt"
},
bottoms:
{
shorts:"shorts",
jeans:"jeans",
joggers:"joggers",
dresspants:"dress pants",
leggings:"leggings"
},
shoes:
{
boots:"boots",
sneakers: "sneakers",
sandals:"sandals",
flats:"flats"
},
jewelry:
{
rings: "rings",
bracelets:"bracelets",
necklaces: "necklaces",
anklets: "anklets"
},
sweaters: "sweaters",
sweatshirts: "sweatshirts",
hoodies: "hoodies",
accessories:
{
watches:"watches",
glasses:
{
sunglasses: "sunglasses",
reading:"reading"
},
wallets: "wallets",
keychains: "keychains",
lanyards:"lanyards",
belts:"belts"
}
},
kids:
{
girl:
{
tops:
{
poloshirts:"polo shirts",
tshirts: "t-shirts",
buttondown: "button down",
longsleeve:"long sleeve",
vneck:"vneck",
tanktop:"tanktop",
blouse:"blouse",
croptop:"croptop",
drifit: "dri-fit",
dressshirt:"dress shirt"
},
bottoms:
{
shorts:"shorts",
jeans:"jeans",
joggers:"joggers",
skirts:"skirts",
dresspants:"dresspants",
leggings:"leggings"
},
shoes:
{
boots:"boots",
sneakers: "sneakers",
sandals:"sandals",
flats:"flats",
heels:"heels"
},
jewelry:
{
rings: "rings",
bracelets:"bracelets",
necklaces: "necklaces",
anklets: "anklets"
},
sweaters: "sweaters",
sweatshirts: "sweatshirts",
hoodies: "hoodies",
dresses:
{
sundress: "sundress",
short: "short",
long: "long",
maxidress: "maxidress"
},
accessories:
{
watches:"watches",
glasses:
{
sunglasses: "sunglasses",
reading:"reading"
},
wallets: "wallets",
keychains: "keychains",
lanyards:"lanyards",
belts:"belts",
purses:"purses"
}
},
boy:
{
tops:
{
poloshirts:"polo shirts",
tshirts: "t-shirts",
buttondown: "button down",
longsleeve:"long sleeve",
vneck:"vneck",
tanktop:"tanktop",
drifit: "dri-fit",
dressshirt: "dress shirt"
},
bottoms:
{
shorts:"shorts",
jeans:"jeans",
joggers:"joggers",
dresspants:"dress pants",
leggings:"leggings"
},
shoes:
{
boots:"boots",
sneakers: "sneakers",
sandals:"sandals",
flats:"flats"
},
jewelry:
{
rings: "rings",
bracelets:"bracelets",
necklaces: "necklaces",
anklets: "anklets"
},
sweaters: "sweaters",
sweatshirts: "sweatshirts",
hoodies: "hoodies",
accessories:
{
watches:"watches",
glasses:
{
sunglasses: "sunglasses",
reading:"reading"
},
wallets: "wallets",
keychains: "keychains",
lanyards:"lanyards",
belts:"belts"
}
}
}
}
</code></pre>
<p>I tried to iterate through this and then generate html selection with the appropiate options, but I cannot figure it out. The furthest I've gotten is this</p>
<pre><code> let selectionHTML = "";
let paths = (arr)=>{
for(let i in arr){
if(typeof arr[i] == "object" && arr[i] !== null){
selectionHTML += "<optgroup label = '" + i + "'></optgroup>";
paths(arr[i]);
}
}
}
paths(myTypes);
</code></pre>
<p>I've no clue how to go about generating my code.</p>
| 3 | 5,355 |
Apache commons command line execute method is returning exit code -1 when running in tomcat application and throwing ExecuteException
|
<p>Using Aapche commons CommandLine library, i am trying to execute an openssl command in a web application running in tomcat in SLES OS. below is the code snippet -</p>
<pre><code> CommandLine cmd = new CommandLine("/usr/bin/openssl")
.addArgument("genrsa")
.addArgument("-out")
.addArgument("/root/testcert_tomcat.key")
.addArgument("4096");
logger.info("Command - "+ cmd.toString());
DefaultExecutor executor = new DefaultExecutor();
executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
executor.setStreamHandler(new PumpStreamHandler(null, null, null));
executor.setWatchdog(new ExecuteWatchdog(60000));
executor.setExitValue(0);
try {
int exitValue = executor.execute(cmd);
if(exitValue != 0 ){
logger.info("Exit value - "+ exitValue);
}
} catch (IOException ex) {
logger.info("Exception - "+ ex.getMessage());
return false;
}
</code></pre>
<p>command - openssl genrsa -out test.key 4096</p>
<p>same command works fine when running from a normal java code outside tomcat web application or directly from shell command line. If someone has any idea please suggest what could be the issue.</p>
<p>Exception caught - org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)</p>
<p>Not so sure but i tried to check the tomcat user, it is running as root -</p>
<pre><code>libv222:/usr/share/tomcat/webapps # ps auxwww | grep -v grep | grep tomcat
tomcat 13700 27.7 12.3 3610620 498412 ? Ssl 20:20 0:46 /usr/bin/java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=5000,suspend=n -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp -Djava.security.auth.login.config=/usr/share/tomcat/conf/jaas.config -Djava.library.path=/lib/emc/powerpath/remote_tools/latest/ -XX:MaxPermSize=128M -Xms512m -Xmx1536m -classpath /usr/share/tomcat/bin/bootstrap.jar:/usr/share/tomcat/bin/tomcat-juli.jar:/usr/share/java/commons-daemon.jar -Dcatalina.base=/usr/share/tomcat -Dcatalina.home=/usr/share/tomcat -Djava.endorsed.dirs= -Djava.io.tmpdir=/var/cache/tomcat/temp -Djava.util.logging.config.file=/usr/share/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager org.apache.catalina.startup.Bootstrap start
root 16591 0.0 0.0 4244 728 pts/0 S+ 17:34 0:00 tail -f /var/log/tomcat/catalina.out
</code></pre>
| 3 | 1,097 |
Strapi. Server wasn't able to start properly
|
<p>I created new tables in the admin panel, but soon the project closed and there were a lot of errors in the console -
[</p>
<pre><code>2022-08-09 10:17:22.950] debug: ⛔️ Server wasn't able to start properly.
[2022-08-09 10:17:22.951] error: CREATE TABLE `_knex_temp_alter937` (`id` varchar(255) PRIMARY KEY AUTOINCREMENT, `a` varchar(255) NULL, `created_at` datetime NULL, `updated_at` datetime NULL, `published_at` datetime NULL, `created_by_id` integer NULL, `updated_by_id` integer NULL, `type` varchar(255) NULL, `sn` bigint NULL, CONSTRAINT `modems_created_by_id_fk` FOREIGN KEY (`created_by_id`) REFERENCES `admin_users` (`id`) ON DELETE SET NULL, CONSTRAINT `modems_updated_by_id_fk` FOREIGN KEY (`updated_by_id`) REFERENCES `admin_users` (`id`) ON DELETE SET NULL, CONSTRAINT `modems_created_by_id_fk` FOREIGN KEY (`created_by_id`) REFERENCES `admin_users` (`id`) ON DELETE SET NULL, CONSTRAINT `modems_updated_by_id_fk` FOREIGN KEY (`updated_by_id`) REFERENCES `admin_users` (`id`) ON DELETE SET NULL) - AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY
SqliteError: CREATE TABLE `_knex_temp_alter937` (`id` varchar(255) PRIMARY KEY AUTOINCREMENT, `a` varchar(255) NULL, `created_at` datetime NULL, `updated_at` datetime NULL, `published_at` datetime NULL, `created_by_id` integer NULL, `updated_by_id` integer NULL, `type` varchar(255) NULL, `sn` bigint NULL, CONSTRAINT `modems_created_by_id_fk` FOREIGN KEY (`created_by_id`) REFERENCES `admin_users` (`id`) ON DELETE SET NULL, CONSTRAINT `modems_updated_by_id_fk` FOREIGN KEY (`updated_by_id`) REFERENCES `admin_users` (`id`) ON DELETE SET NULL, CONSTRAINT `modems_created_by_id_fk` FOREIGN KEY (`created_by_id`) REFERENCES `admin_users` (`id`) ON DELETE SET NULL, CONSTRAINT `modems_updated_by_id_fk` FOREIGN KEY (`updated_by_id`) REFERENCES `admin_users` (`id`) ON DELETE SET NULL) - AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY
at Database.prepare (/home/daniil/counter/node_modules/better-sqlite3/lib/methods/wrappers.js:5:21)
at Client_BetterSQLite3._query (/home/daniil/counter/node_modules/knex/lib/dialects/better-sqlite3/index.js:30:34)
at executeQuery (/home/daniil/counter/node_modules/knex/lib/execution/internal/query-executioner.js:37:17)
at Client_BetterSQLite3.query (/home/daniil/counter/node_modules/knex/lib/client.js:146:12)
at /home/daniil/counter/node_modules/knex/lib/execution/transaction.js:363:24
at new Promise (<anonymous>)
at Client_BetterSQLite3.trxClient.query (/home/daniil/counter/node_modules/knex/lib/execution/transaction.js:358:12)
at Runner.query (/home/daniil/counter/node_modules/knex/lib/execution/runner.js:130:36)
at Runner.queryArray (/home/daniil/counter/node_modules/knex/lib/execution/runner.js:224:21)
at Runner.queryArray (/home/daniil/counter/node_modules/knex/lib/execution/runner.js:276:31)
</code></pre>
<p>Please help how to solve this problem? Restarting the project doesn't help.</p>
| 3 | 1,177 |
How to animate sliding on an image slider
|
<p>I wrote this code for a image slider but i don't know how to make a sliding animation when swapping throw photos</p>
<p>So, if anyone can help I would be grateful.</p>
<p>html :-</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Slider</title>
<!-- CSS -->
<link rel="stylesheet" href="index.css">
</head>
<body>
<div id="container">
<img id="first" class="slide" src="https://upload.wikimedia.org/wikipedia/commons/c/ca/Fiat_127_2_v_sst.jpg" alt="">
<img class="slide" src="https://trustspringer.com/wp-content/uploads/2019/07/house-mouse-1.jpg" alt="">
<img class="slide" src="https://www.dw.com/image/40734768_303.jpg" alt="">
<img class="slide" src="https://icatcare.org/app/uploads/2018/07/Thinking-of-getting-a-cat.png" alt="">
<button id="prev">prev</button>
<button id="next">next</button>
</div>
<!-- JavaScript -->
<script src="index.js"></script>
</code></pre>
<p>css :-</p>
<pre><code>img{
width: 60%;
margin-left: 20%;
height: 50vh;
display: none;
}
#first{
display: block;
}
</code></pre>
<p>javascript :-</p>
<pre><code>var images = document.querySelectorAll(".slide"),
prev = document.getElementById("prev"),
next = document.getElementById("next"),
count = 0;
next.addEventListener("click", function() {
images[count].style.display = "none";
if(count >= images.length - 1) {
count = 0;
} else {
count ++;
}
images[count].style.display = "block";
});
prev.addEventListener("click", function() {
images[count].style.display = "none";
if(count <= 0) {
count = images.length - 1;
} else {
count --;
}
images[count].style.display = "block";
});
</code></pre>
<p>......................................................
......................................................
......................................................
......................................................
......................................................
......................................................
......................................................</p>
<p>Thanks</p>
| 3 | 1,059 |
Run maven project-info-reports:dependencies with a pom.xml
|
<p>I want to include my dependencies.html into a warfile in a multi module project. When i run mvn project-info-reports:dependencies the folder site gets created with the dependencies.html file in it. Is there a way to do this with a pom.xml file?
Things that did not work have been:</p>
<pre><code><build>
<finalName>some-module</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>dependencies</id>
<goals>
<goal>dependencies</goal>
</goals>
...
</code></pre>
<p>or this one:</p>
<pre><code><reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.9</version>
<reportSets>
<reportSet>
<configuration>
<skip>true</skip>
</configuration>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.9</version>
<reportSets>
<reportSet>
<reports>
<report>index</report>
<report>dependencies</report>
</reports>
</reportSet>
</reportSets>
</plugin>
</plugins>
</reporting>
<build>
<finalName>some-module</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.2</version>
<executions>
<execution>
<id>dependencies</id>
<goals>
<goal>site</goal>
</goals>
...
</code></pre>
<p>There is no error message in the logs, it just gets skipped. Am i doing something wrong here or is it just not meant to execute with the pom.xml?</p>
| 3 | 1,467 |
How to parse into records?
|
<p>I have a asked a question before, which I learned from. I discovered that the implementation resulted in a list of strings rather than a list of records. The file I am parsing has records that looks like;</p>
<blockquote>
<p>sp|P30375|1A01_GORGO Class I histocompatibility antigen Gogo-A*0101 alpha chain OS=Gorilla gorilla gorilla PE=2 SV=1
MAVMAPRTLVLLLSGALALTQTWAGSHSMRYFSTSVSRPGRGEPRFIAVGYVDDTQFVRF
DSDAASQRMEPRAPWIEQEGPEYWDRNTRNVKAHSQTDRVDLGTLRGYYNQSEDGSHTIQ
RMYGCDVGSDGRFLRGYQQDAYDGKDYIALNEDLRSWTAADMAAEITKRKWEAAHFAEQL
RAYLEGTCVEWLRRHLENGKETLQRTDAPKTHMTHHAVSDHEAILRCWALSFYPAEITLT
WQRDGEDQTQDTELVETRPAGDGTFQKWAAVVVPSGQEQRYTCHVQHEGLPEPLTLRWEP
SSQPTIPIVGIIAGLVLFGAVIAGAVVAAVRWRRKSSDRKGGSYSQAASSDSAQGSDVSL
TACKV
sp|P30443|1A01_HUMAN HLA class I histocompatibility antigen A-1 alpha chain OS=Homo sapiens GN=HLA-A PE=1 SV=1
MAVMAPRTLLLLLSGALALTQTWAGSHSMRYFFTSVSRPGRGEPRFIAVGYVDDTQFVRF
DSDAASQKMEPRAPWIEQEGPEYWDQETRNMKAHSQTDRANLGTLRGYYNQSEDGSHTIQ
IMYGCDVGPDGRFLRGYRQDAYDGKDYIALNEDLRSWTAADMAAQITKRKWEAVHAAEQR
RVYLEGRCVDGLRRYLENGKETLQRTDPPKTHMTHHPISDHEATLRCWALGFYPAEITLT
WQRDGEDQTQDTELVETRPAGDGTFQKWAAVVVPSGEEQRYTCHVQHEGLPKPLTLRWEL
SSQPTIPIVGIIAGLVLLGAVITGAVVAAVMWRRKSSDRKGGSYTQAASSDSAQGSDVSL
TACKV </p>
</blockquote>
<p>just before the sp there is a ">", which I planned to use as a records divide point. So, how can I end up with:</p>
<pre><code>[[>sp|P30375|1A01_GORGO Class I histocompatibility antigen Gogo-A*0101 alpha chain OS=Gorilla gorilla gorilla PE=2 SV=1
MAVMAPRTLVLLLSGALALTQTWAGSHSMRYFSTSVSRPGRGEPRFIAVGYVDDTQFVRF
DSDAASQRMEPRAPWIEQEGPEYWDRNTRNVKAHSQTDRVDLGTLRGYYNQSEDGSHTIQ
RMYGCDVGSDGRFLRGYQQDAYDGKDYIALNEDLRSWTAADMAAEITKRKWEAAHFAEQL
RAYLEGTCVEWLRRHLENGKETLQRTDAPKTHMTHHAVSDHEAILRCWALSFYPAEITLT
WQRDGEDQTQDTELVETRPAGDGTFQKWAAVVVPSGQEQRYTCHVQHEGLPEPLTLRWEP
SSQPTIPIVGIIAGLVLFGAVIAGAVVAAVRWRRKSSDRKGGSYSQAASSDSAQGSDVSL
TACKV]
[>sp|P30443|1A01_HUMAN HLA class I histocompatibility antigen A-1 alpha chain OS=Homo sapiens GN=HLA-A PE=1 SV=1
MAVMAPRTLLLLLSGALALTQTWAGSHSMRYFFTSVSRPGRGEPRFIAVGYVDDTQFVRF
DSDAASQKMEPRAPWIEQEGPEYWDQETRNMKAHSQTDRANLGTLRGYYNQSEDGSHTIQ
IMYGCDVGPDGRFLRGYRQDAYDGKDYIALNEDLRSWTAADMAAQITKRKWEAVHAAEQR
RVYLEGRCVDGLRRYLENGKETLQRTDPPKTHMTHHPISDHEATLRCWALGFYPAEITLT
WQRDGEDQTQDTELVETRPAGDGTFQKWAAVVVPSGEEQRYTCHVQHEGLPKPLTLRWEL
SSQPTIPIVGIIAGLVLLGAVITGAVVAAVMWRRKSSDRKGGSYTQAASSDSAQGSDVSL
TACKV]]
</code></pre>
<p>using parsec? This is the code I started out with; <a href="https://stackoverflow.com/questions/29380363/how-to-parse-a-uniprot-file-with-parsec">how to parse a uniprot-file with parsec?</a></p>
| 3 | 1,341 |
Finding a non related child element from a $this click event
|
<p>I have a jquery code that when the user clicks on the menu button (Example: Donation button) it changes the article section of the page (Not related directly as a child to the menu section) pulling new information with javascript. The DOM does not show this new information so when I try to apply a CSS class, it does not work.</p>
<p>How can I click on the donation button so it creates the new information in the article section BUT it also applies the CSS class to it.</p>
<p>Here is part of the code to give an idea:</p>
<h2>JAVASCRIPT</h2>
<pre><code> $(document).on('click', '.menu', function () {
var option = $(this).text().replace(/á/g, 'a').replace(/é/g, 'e').replace(/í/g, 'i').replace(/ó/g, 'o').replace(/ú/g, 'u').toLowerCase();
$('.active').removeClass("active");
$(this).addClass("active");
$('#context').html(menu[option]).find('form').addClass("centerB");
change = true;
});
</code></pre>
<h2>HTML</h2>
<pre><code><div class="secContainer"></div>
<nav>
<ul>
<li><a href="index.html" id="index" class="menu">Home</a></li>
<li><a href="#" class="menu">Population</a></li>
<li><a href="#" class="menu">Life Style</a></li>
<li><a href="#" class="menu">Work</a></li>
<li><a href="#" class="menu">Comments</a></li>
<li><a href="#" class="menu">Gallery</a></li>
<li class="last"><a href="#" class="menu">Donations</a></li>
</ul>
.....
<article id="context">
<h2>HISTORY</h2>
<p>Indians once lived with machine guns and aliens. They formed highly trained tech industries and ate bananas. They trained playing mario bros all day long until reaching the boss in less than 5 minutes.</p>
</article>
</code></pre>
<p>Basically they click on the Donation button on the main menu. This changes the content of the article element to something else. This something else is not available directly in the loading on the web page, instead, it is pulled from a javascript object that has the text.</p>
<p>This line takes care of changing the context:</p>
<pre><code> $('#context').html(menu[option]).find('form').addClass("centerB");
</code></pre>
<p>I added the ".find('form').addClass("centerB");" to see if it worked. It did not. I wanted to apply a CSS to the recently pulled information. How can I apply a CSS or another change to this type of nonexisting dom information. Please correct me if my terminology or knowledge about it is wrong and also if you think a better title could be appropriate.</p>
| 3 | 1,199 |
Why isn't ul using full nav's height?
|
<p>I'm having some problems creating a header.
<a href="https://imgur.com/a/qxnzusq" rel="nofollow noreferrer">Here</a>, my ul is not using the full height of the nav, but the nav IS using the full height of the header.
I want to fix this in order to center vertically the text.
Thank you.</p>
<p>(edit) When I use <code>height: 100%;</code> on the ul, <a href="https://imgur.com/a/c6vnrun" rel="nofollow noreferrer">this</a> happens.</p>
<p>This is my HTML:</p>
<pre><code> <header>
<div class="logo">
<img src="img/logo.png"/>
</div>
<nav>
<ul>
<li><a href="#">HOME</a></li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">WORKS</a></li>
<li><a href="#">CONTACT</a></li>
</ul>
</nav>
</header>
</code></pre>
<p>This is my SASS:</p>
<pre><code>$BLACK:#000;
$WHITE:#fff;
* {
box-sizing: border-box;
}
header {
width: 100%;
height: 75px;
background-color: $BLACK;
display: flex;
flex-flow: row wrap;
justify-content: space-between;
.logo {
width: 50%;
display: flex;
align-items: center;
padding-left: 50px;
}
nav {
width: 50%;
padding-right: 50px;
ul {
list-style-type: none;
display: flex;
flex-flow: row wrap;
justify-content: right;
li {
display: inline-block;
margin-left:50px;
a {
text-decoration: none;
color: $WHITE;
}
}
}
}
}
</code></pre>
| 3 | 1,064 |
Get icon of installed apps on WebOS TV LG
|
<p>I'm making a sample about remote on LG TV using webOS with ConnectSDK. I can remote with some basic command, get the list of installed apps on the TV. The data of each item like this:</p>
<pre><code>["type": native, "handlesRelaunch": 0, "uiRevision": 2, "deeplinkingParams": {"contentTarget":"https://www.youtube.com/tv?launch=search&v=$CONTENTID"}, "wolwowlan": 1, "icon": https://192.168.100.71:3001/resources/ed06d6cb588bfaac4181742c2266ba1586671791/yt_lg_80x80.png, "checkUpdateOnLaunch": 1, "icons": <__NSArray0 0x7fff8062d430>(
)
, "inAppSetting": 0, "id": youtube.leanback.v4, "splashBackground": 2018-new-splash-solid-grey-LG.png, "supportQuickStart": 1, "version": 1.3.86, "systemApp": 0, "hasPromotion": 0, "removable": 1, "unmovable": 0, "dialAppName": YouTube, "lockable": 1, "bgImage": 9262051282473701_youtube_leanback_preview.png, "trustLevel": default, "resolution": 1280x720, "inspectable": 0, "binId": 972014, "vendor": LG Electronics, "defaultWindowType": card, "main": cobalt, "tileSize": normal, "installTime": 1587515064, "spinnerOnLaunch": 1, "privilegedJail": 1, "imageForRecents": 9262051307371701_youtube_leanback_splash.png, "folderPath": /media/cryptofs/apps/usr/palm/applications/youtube.leanback.v4, "title": YouTube, "appsize": 24847139, "disableBackHistoryAPI": 0, "nativeLifeCycleInterfaceVersion": 2, "largeIcon": yt_lg_130x130.png, "transparent": 0, "iconColor": #ffffff, "mediumLargeIcon": 15290169578796633_16977867_115x115.png, "accessibility": {
supportsAudioGuidance = 0;
}, "enablePigScreenSaver": 0, "noSplashOnLaunch": 0, "CPApp": 0, "visible": 1, "requiredEULA": generalTerms]
</code></pre>
<p>With above data, I have url of icon: <code>https://192.168.100.71:3001/resources/ed06d6cb588bfaac4181742c2266ba1586671791/yt_lg_80x80.png</code></p>
<p>But I can't get icon from this url, like this issue:
<a href="https://github.com/ConnectSDK/Connect-SDK-iOS/issues/191" rel="nofollow noreferrer">https://github.com/ConnectSDK/Connect-SDK-iOS/issues/191</a></p>
<p>I can't find any document about this.</p>
<p>Can anyone help me?</p>
<p>Thanks a lot!</p>
| 3 | 1,143 |
How best to expose properties of a native Android control in a control derived from a Xamarin forms view
|
<p>Fair warning: I am new to Android, Xamarin Forms and MVVM (though I am a seasoned desktop Windows application developer). And though I have used SO as a valuable resource for years, this is my first posted question. So I know I have a lot to learn, and I would appreciate any feedback.</p>
<p>For my project, I need a read-only multi-line text view (Xamarin Editor) that offers selectable text. Poking around SO and other places, I saw how to implement a custom Editor Renderer. This was pretty straight forward and seems to work well:</p>
<ul>
<li>a keyboard is not displayed when the Editor is focused</li>
<li>the user can select and copy text</li>
<li>the context menu (displayed when text is selected) contains only <strong>Copy</strong> and <strong>Select All</strong></li>
</ul>
<p>Most of the code below was taken from a medium.com post: <a href="https://medium.com/@anna.domashych/selectable-read-only-multiline-text-field-on-android-169c27c55408" rel="nofollow noreferrer">https://medium.com/@anna.domashych/selectable-read-only-multiline-text-field-on-android-169c27c55408</a> (thank you Anna!)</p>
<p>Working in VS 2019, my shared project has a simple class derived from Editor, which is named <strong>SelectableLabel</strong>.</p>
<pre><code>namespace RO_Editor
{
public class SelectableLabel : Editor
{
}
}
</code></pre>
<p>The Android project has the custom renderer:</p>
<pre><code>[assembly: ExportRenderer(typeof(SelectableLabel), typeof(SelectableLabelRenderer))]
namespace RO_Editor
{
class SelectableLabelRenderer : EditorRenderer
{
public SelectableLabelRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
if (Control == null)
return;
Control.Background = null;
Control.SetPadding(0, 0, 0, 0);
Control.ShowSoftInputOnFocus = false;
Control.SetTextIsSelectable(true);
Control.CustomSelectionActionModeCallback = new CustomSelectionActionModeCallback();
Control.CustomInsertionActionModeCallback = new CustomInsertionActionModeCallback();
}
private class CustomInsertionActionModeCallback : Java.Lang.Object, ActionMode.ICallback
{
public bool OnCreateActionMode(ActionMode mode, IMenu menu) => false;
public bool OnActionItemClicked(ActionMode m, IMenuItem i) => false;
public bool OnPrepareActionMode(ActionMode mode, IMenu menu) => true;
public void OnDestroyActionMode(ActionMode mode) { }
}
private class CustomSelectionActionModeCallback : Java.Lang.Object, ActionMode.ICallback
{
private const int CopyId = Android.Resource.Id.Copy;
private const int SelAllId = Android.Resource.Id.SelectAll;
public bool OnActionItemClicked(ActionMode m, IMenuItem i) => false;
public bool OnCreateActionMode(ActionMode mode, IMenu menu) => true;
public void OnDestroyActionMode(ActionMode mode) { }
public bool OnPrepareActionMode(ActionMode mode, IMenu menu)
{
try
{
IMenuItem copyItem = menu.FindItem(CopyId);
var title = copyItem.TitleFormatted;
IMenuItem selAllItem = menu.FindItem(SelAllId);
var selAllTitle = selAllItem.TitleFormatted;
menu.Clear();
menu.Add(0, CopyId, 0, title);
menu.Add(0, SelAllId, 1, selAllTitle);
}
catch
{
// ignored
}
return true;
}
}
}
}
</code></pre>
<p>That's what I'm working with thus far. My next task is to offer a search function. That is, allow the user to specify a search string (via SearchBar) and to programmatically find the search string in the SelectableLabel text, and to select the search hits in the SelectableLabel view.</p>
<p>The Xamarin Editor maps to a native Android TextEdit view. TextEdit has a SetSelection() method, and I'd like to expose this method in my SelectableLabel control. What is a generally accepted way to do this?</p>
| 3 | 1,742 |
When I run "vagrant up" on Windows 10 then I get errors
|
<p>I use Vagrant 1.9.2 and PHP 7.1.3</p>
<pre><code>C:\Users\LUONG HUNG\Code>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'base' could not be found. Attempting to find and install...
default: Box Provider: virtualbox
default: Box Version: >= 0
C:/HashiCorp/Vagrant/embedded/lib/ruby/2.2.0/uri/rfc3986_parser.rb:66:in `split': bad URI(is not URI?): file:///C:/Users/LUONG HUNG/Code/base (URI::InvalidURIError)
from C:/HashiCorp/Vagrant/embedded/lib/ruby/2.2.0/uri/rfc3986_parser.rb:72:in `parse'
from C:/HashiCorp/Vagrant/embedded/lib/ruby/2.2.0/uri/common.rb:226:in `parse'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/box_add.rb:475:in `metadata_url?'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/box_add.rb:81:in `block in call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/box_add.rb:79:in `map'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/box_add.rb:79:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builder.rb:116:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `block in run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/util/busy.rb:19:in `busy'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/handle_box.rb:82:in `handle_box'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/handle_box.rb:42:in `block in call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/handle_box.rb:36:in `synchronize'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/handle_box.rb:36:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:95:in `block in finalize_action'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builder.rb:116:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `block in run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/util/busy.rb:19:in `busy'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/call.rb:53:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/plugins/providers/virtualbox/action/check_virtualbox.rb:17:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builder.rb:116:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `block in run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/util/busy.rb:19:in `busy'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/machine.rb:225:in `action_raw'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/machine.rb:200:in `block in action'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/environment.rb:567:in `lock'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/machine.rb:186:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/machine.rb:186:in `action'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/batch_action.rb:82:in `block (2 levels) in run'
C:\Users\LUONG HUNG\Code>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'base' could not be found. Attempting to find and install...
default: Box Provider: virtualbox
default: Box Version: >= 0
C:/HashiCorp/Vagrant/embedded/lib/ruby/2.2.0/uri/rfc3986_parser.rb:66:in `split': bad URI(is not URI?): file:///C:/Users/LUONG HUNG/Code/base (URI::InvalidURIError)
from C:/HashiCorp/Vagrant/embedded/lib/ruby/2.2.0/uri/rfc3986_parser.rb:72:in `parse'
from C:/HashiCorp/Vagrant/embedded/lib/ruby/2.2.0/uri/common.rb:226:in `parse'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/box_add.rb:475:in `metadata_url?'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/box_add.rb:81:in `block in call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/box_add.rb:79:in `map'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/box_add.rb:79:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builder.rb:116:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `block in run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/util/busy.rb:19:in `busy'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/handle_box.rb:82:in `handle_box'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/handle_box.rb:42:in `block in call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/handle_box.rb:36:in `synchronize'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/handle_box.rb:36:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:95:in `block in finalize_action'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builder.rb:116:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `block in run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/util/busy.rb:19:in `busy'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builtin/call.rb:53:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/plugins/providers/virtualbox/action/check_virtualbox.rb:17:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/warden.rb:34:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/builder.rb:116:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `block in run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/util/busy.rb:19:in `busy'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/action/runner.rb:66:in `run'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/machine.rb:225:in `action_raw'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/machine.rb:200:in `block in action'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/environment.rb:567:in `lock'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/machine.rb:186:in `call'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/machine.rb:186:in `action'
from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-1.9.2/lib/vagrant/batch_action.rb:82:in `block (2 levels) in run'
</code></pre>
| 3 | 4,486 |
C# Unexpected performance results for different methods of parsing byte[] as hex string
|
<p>I have created 3 different methods for converting a <code>byte[]</code> into a hex string using the following format: <code>{ 0xx2, ... }</code> (<a href="https://dotnetfiddle.net/UOHHXo" rel="nofollow noreferrer">Working Demo</a>)</p>
<pre><code>using System;
using System.Diagnostics;
using System.Text;
public class Program
{
public delegate string ParseMethod(byte[] Msg);
public class Parser
{
public string Name { get; private set;}
public ParseMethod Handler { get; private set; }
public Parser(string name, ParseMethod method)
{
Name = name;
Handler = method;
}
}
public static void Main()
{
Parser HexA = new Parser("ToHexA", ToHexA);
Parser HexB = new Parser("ToHexB", ToHexB);
Parser HexC = new Parser("ToHexC", ToHexC);
TestCorrectness(HexA);
TestCorrectness(HexB);
TestCorrectness(HexC);
Console.WriteLine("Small Message Performance:");
TestPerformance(HexA, MsgSize: 10, Iterations: 1000000);
TestPerformance(HexB, MsgSize: 10, Iterations: 1000000);
TestPerformance(HexC, MsgSize: 10, Iterations: 1000000);
Console.WriteLine();
Console.WriteLine("Large Message Performance:");
TestPerformance(HexA, MsgSize: 500, Iterations: 1000000);
TestPerformance(HexB, MsgSize: 500, Iterations: 1000000);
TestPerformance(HexC, MsgSize: 500, Iterations: 1000000);
Console.WriteLine();
}
private static void TestCorrectness(Parser parser)
{
Console.WriteLine("Testing Correctness of \"{0}(byte[] Msg)\"", parser.Name);
Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{}));
Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{ 97 }));
Console.WriteLine("\"{0}\"", parser.Handler(new byte[]{ 97, 98, 99, 0, 100 }));
Console.WriteLine();
}
private static void TestPerformance(Parser parser, int MsgSize, int Iterations)
{
Stopwatch sw = new Stopwatch();
sw.Reset();
byte[] Msg = new byte[MsgSize];
sw.Start();
for (uint i = 0; i < Iterations; ++i)
{
parser.Handler(Msg);
}
sw.Stop();
Console.WriteLine("Performance for \"{0}\", {1}", parser.Name, sw.Elapsed);
}
private static string ToHexA(byte[] buffer)
{
return
(
"{ 0x" +
BitConverter.ToString(buffer).ToLower()
.Replace("-", ", 0x") +
" }"
)
.Replace(" 0x }", "}");
}
private static string ToHexB(byte[] buffer)
{
if (buffer.Length == 0) { return "{}"; }
const string Preamble = "{ 0x";
const string Delimiter = ", 0x";
const string Epilogue = " }";
string Msg = Preamble + buffer[0].ToString("x2");
for (int i = 1; i < buffer.Length; ++i)
{
Msg += Delimiter + buffer[i].ToString("x2");
}
return Msg += Epilogue;
}
private static string ToHexC(byte[] buffer)
{
if (buffer.Length == 0) { return "{}"; }
const string Preamble = "{ 0x";
const string Delimiter = ", 0x";
const string Epilogue = " }";
StringBuilder HexOut = new StringBuilder(
Preamble.Length +
(Delimiter.Length * (buffer.Length - 1)) +
(2 * buffer.Length) +
Epilogue.Length
);
HexOut.Append(Preamble);
HexOut.Append(buffer[0].ToString("x2"));
for (int i = 1; i < buffer.Length; ++i)
{
HexOut.Append(Delimiter);
HexOut.Append(buffer[i].ToString("x2"));
}
HexOut.Append(Epilogue);
return HexOut.ToString();
}
}
</code></pre>
<p>Running this code I get the following performance statistics</p>
<pre><code>Small Message Performance:
Performance for "ToHexA", 00:00:01.3078387
Performance for "ToHexB", 00:00:01.6939201
Performance for "ToHexC", 00:00:01.2997903
Large Message Performance:
Performance for "ToHexA", 00:00:32.5230253
Performance for "ToHexB", 00:04:23.4798762
Performance for "ToHexC", 00:00:56.2404684
</code></pre>
<p>I find it surprising that <code>ToHexA</code> (relative to <code>ToHexC</code>) executes faster with a longer message but slower with a shorter message. As I understand it, <code>Replace()</code>, <code>+</code>, and <code>ToLower()</code> all have to perform a create/copy operation because strings are immutable.</p>
<p>At the same time, I suspected the overhead for StringBuilder might make it less suitable for shorter messages yet it executes faster than <code>ToHexA</code> in this situation.</p>
<p>The only thing I expected was the performance hit associated with <code>ToHexB</code> which is kind of an in between worst of both worlds scenario...</p>
<p>So, what is going on with these two methods and their performance characteristics?</p>
<p><strong><h1>Edit to make my intentions with this question more clear</h1></strong></p>
<p>I am not particularly interested in exact performance characteristics of two methods that are closely performant. I am aware this will be different on different devices, architectures, background processes, etc etc. and better testing methods exist to control variables and what not</p>
<p>My purpose in asking this question was to better understand why two noticeably dissimilar (in terms of performance) approaches stack up the way they do. The accepted answer explains the mechanics of <code>ToString</code> in a way that satisfies this question.</p>
<p>One constraint of this question the exact formatting of the output was specific and (we can only muse why, I think it's pretty standard) for some reason not one of the standard output formats in C#/.NET; it was this unique format that led to the question: stacking multiple replace and concatenation operations against <code>StringBuilder</code></p>
| 3 | 2,375 |
Xamarin.iOS SIGSEGV when trying to discover services of a connected BLE peripheral
|
<p>I'm making a BLE cross-platform app in Xamarin, but fail to discover services of a connected peripheral.</p>
<p>Here's the stripped down code from the shared-project, just to be able to reproduce this issue;</p>
<pre><code>internal class BleTransport
{
//Private stuff
private CBCentralManager Central = null;
private CBPeripheral CurrentPeripheral = null;
private bool IsScanning = false;
internal BleTransport ()
{
//Constructor -- initialize everything that needs to be initialized!
Central = new CBCentralManager (DispatchQueue.MainQueue);
//Setup delegates to the central's events
Central.UpdatedState += (object sender, EventArgs e) => CentralStateChanged.Set ();
Central.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) => DiscoveredPeripheral (e.Peripheral, e.RSSI, e.AdvertisementData);
Central.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) => ConnectedPeripheral (e.Peripheral);
Central.FailedToConnectPeripheral += (object sender, CBPeripheralErrorEventArgs e) => FailedToConnectPeripheral (e.Error, e.Peripheral);
Central.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) => DisconnectedPeripheral (e.Error, e.Peripheral);
}
readonly AutoResetEvent CentralStateChanged = new AutoResetEvent (false);
private async Task<bool> WaitForCentralState (CBCentralManagerState state, TimeSpan timespan)
{
Console.WriteLine("Waiting for state : " + state);
//TODO; Keep track of time and decrease time-span accordingly
bool timedout = false;
while (!timedout && Central.State != state)
{
timedout = await Task.Run (delegate {
//WaitOne returns false if we timeout
return !CentralStateChanged.WaitOne (timespan);
});
}
//Return true if we made it, amd false if we timedout
return !timedout;
}
private void StartScanning()
{
Console.WriteLine("Start scan requestd!");
if (!IsScanning)
{
//Start!
IsScanning = true;
Console.WriteLine("Kicking scan for peripherals!");
CBUUID[] uuids = null;
Central.ScanForPeripherals (uuids);
}
}
private void StopScanning()
{
Console.WriteLine("Stop scan requested!");
if (IsScanning)
{
//Stop!
IsScanning = false;
Central.StopScan();
}
}
public async Task<bool> SetupTransport ()
{
Console.WriteLine("Setting up transport!");
//Wait for state update...
if (!await WaitForCentralState (CBCentralManagerState.PoweredOn, TimeSpan.FromSeconds (2))) {
//Failed detecting a powered-on BLE interface
Console.WriteLine("Failed detecting usable BLE interface!");
return false;
}
//Kick scanning...
StartScanning();
//Wait for discovery and connection to a valid peripheral, or timeout trying...
await Task.Delay(10000);
return true;
}
#region Internal BLE utility methods
private void DiscoveredPeripheral (CBPeripheral peripheral, NSNumber rssi, NSDictionary advertisementData)
{
Console.WriteLine("DiscoveredPeripheral: " +peripheral.Name);
//If the discovered device's name IS a valid serial number, AND match the serial number that we're intended to establish connection to...
if (peripheral.Name == "MyPeripheralName") {
Console.WriteLine("It's the peripheral we're looking for!");
//Stop scanning...
StopScanning();
//Save reference and connect to it!
CurrentPeripheral = peripheral;
Central.ConnectPeripheral(CurrentPeripheral, new PeripheralConnectionOptions());
}
}
private void ConnectedPeripheral (CBPeripheral peripheral)
{
Console.WriteLine("ConnectedPeripheral: " + peripheral.Name);
//Great -- explore services and charateristics and don't stop until we know that this device is legit!
CurrentPeripheral.DiscoveredService += (object sender, NSErrorEventArgs e) => DiscoveredServices (e.Error);
CurrentPeripheral.DiscoveredCharacteristic += (object sender, CBServiceEventArgs e) => DiscoveredCharacteristics (e.Error, e.Service);
//Kick service discovery!
CurrentPeripheral.DiscoverServices();
}
private void FailedToConnectPeripheral (NSError error, CBPeripheral peripheral)
{
Console.WriteLine("FailedToConnectPeripheral: " + peripheral.Name);
}
private void DisconnectedPeripheral (NSError error, CBPeripheral peripheral)
{
Console.WriteLine("DisconnectedPeripheral: " + peripheral.Name + "(Error = " + error + ")");
}
private void DiscoveredServices (NSError error)
{
Console.WriteLine("DiscoveredService: " + error + " -- " + NSThread.Current.IsMainThread);
if (error != null) {
//No error -- great!
foreach (CBService service in CurrentPeripheral.Services) {
Console.WriteLine ("Discovered service: " + service);
}
}
else
{
//Opps -- failed!
//Disconnect and indicate connection attempt finished
}
}
private void DiscoveredCharacteristics (NSError error, CBService service)
{
Console.WriteLine("DiscoveredCharacteristics for service: " + service);
if (error != null) {
//No error -- great!
foreach (CBCharacteristic characteristic in service.Characteristics) {
Console.WriteLine ("Discovered charateristic: " + characteristic);
}
}
else
{
//Opps -- failed!
//Disconnect and indicate connection attempt finished
}
}
#endregion
}
</code></pre>
<p>The problem is that AFTER discovery is done, scanning is stopped, and the app connect to the peripheral and we arrive in the <em>ConnectedPeripheral (CBPeripheral peripheral)</em> function, I get a SIGSEGV crash with the following stack trace;</p>
<pre><code>2015-04-21 23:33:37.205 BLE-test[1487:322866] critical: Stacktrace:
2015-04-21 23:33:37.206 BLE-test[1487:322866] critical: at <unknown> <0xffffffff>
2015-04-21 23:33:37.206 BLE-test[1487:322866] critical: at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain (int,string[],intptr,intptr) <0xffffffff>
2015-04-21 23:33:37.207 BLE-test[1487:322866] critical: at UIKit.UIApplication.Main (string[],intptr,intptr) [0x00005] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:62
2015-04-21 23:33:37.207 BLE-test[1487:322866] critical: at UIKit.UIApplication.Main (string[],string,string) [0x0001c] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:45
2015-04-21 23:33:37.208 BLE-test[1487:322866] critical: at BLEtest.Application.Main (string[]) [0x00008] in /Users/markus/Xamarin/BLE-test/BLE-test/Main.cs:17
2015-04-21 23:33:37.208 BLE-test[1487:322866] critical: at (wrapper runtime-invoke) object.runtime_invoke_dynamic (intptr,intptr,intptr,intptr) <0xffffffff>
</code></pre>
<p>Followed by a native stack-trace that I've symbolicated into;</p>
<pre><code>Incident Identifier: DCFCEE70-3D12-4F69-8303-777B2959563D
CrashReporter Key: 25c23a5bf636eb183168b18867096174f0d59b79
Hardware Model: iPhone6,2
Process: BLE-test [1241]
Path: /private/var/mobile/Containers/Bundle/Application/C091012A-B1CB-464B-BDA5-B193C9C26BFC/BLE-test.app/BLE-test
Identifier: com.your-company.BLEtest
Version: 1.0 (1.0)
Code Type: ARM-64 (Native)
Parent Process: launchd [1]
Date/Time: 2015-04-21 22:22:57.387 +0200
Launch Time: 2015-04-21 22:22:56.120 +0200
OS Version: iOS 8.3 (12F70)
Report Version: 105
Exception Type: EXC_BAD_ACCESS (SIGABRT)
Exception Subtype: KERN_INVALID_ADDRESS at 0x000000000004b2c0
Triggered by Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x0000000195233270 __pthread_kill + 8
1 libsystem_pthread.dylib 0x00000001952d116c pthread_kill + 108
2 libsystem_c.dylib 0x00000001951aab14 abort + 108
3 BLE-test 0x00000001001f6878 mono_handle_native_sigsegv (mini-exceptions.c:2360)
4 BLE-test 0x0000000100200554 mono_sigsegv_signal_handler (mini.c:6879)
5 libsystem_platform.dylib 0x00000001952c8958 _sigtramp + 64
6 libobjc.A.dylib 0x0000000194aa5ea8 _class_getVariable + 160
7 libobjc.A.dylib 0x0000000194aa5ea8 _class_getVariable + 160
8 libobjc.A.dylib 0x0000000194a9a934 object_getInstanceVariable + 72
9 BLE-test 0x00000001002b10b0 get_raw_gchandle (runtime.m:304)
10 BLE-test 0x00000001002b1044 get_gchandle (runtime.m:311)
11 BLE-test 0x00000001002b0c6c xamarin_get_gchandle (runtime.m:317)
12 BLE-test 0x00000001002b0bc0 xamarin_get_nsobject_with_type_for_ptr_created (runtime.m:201)
13 BLE-test 0x00000001002b9508 xamarin_trampoline (.monotouch-trampoline-setup-callstack.inc:181)
14 CoreBluetooth 0x0000000182f37198 -[CBPeripheral handleServicesDiscovered:] + 740
15 CoreBluetooth 0x0000000182f34b38 -[CBPeripheral handleMsg:args:] + 280
16 CoreBluetooth 0x0000000182f309d0 -[CBCentralManager xpcConnection:didReceiveMsg:args:] + 160
17 libdispatch.dylib 0x00000001950ed990 _dispatch_call_block_and_release + 20
18 libdispatch.dylib 0x00000001950ed950 _dispatch_client_callout + 12
19 libdispatch.dylib 0x00000001950f80a0 _dispatch_queue_drain + 1444
20 libdispatch.dylib 0x00000001950f0a58 _dispatch_queue_invoke + 128
21 libdispatch.dylib 0x00000001950f1db8 _dispatch_main_queue_callback_4CF + 500
22 CoreFoundation 0x000000018327f7f4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 8
23 CoreFoundation 0x000000018327d89c __CFRunLoopRun + 1488
24 CoreFoundation 0x00000001831a92d0 CFRunLoopRunSpecific + 392
25 GraphicsServices 0x000000018c9c76f8 GSEventRunModal + 164
26 UIKit 0x0000000187d6efa8 UIApplicationMain + 1484
27 BLE-test 0x00000001000a0b94 wrapper_managed_to_native_UIKit_UIApplication_UIApplicationMain_int_string___intptr_intptr + 340
28 BLE-test 0x000000010007e60c UIKit_UIApplication_Main_string___intptr_intptr + 44
29 BLE-test 0x000000010007e5c8 UIKit_UIApplication_Main_string___string_string + 184
30 BLE-test 0x0000000100050110 BLEtest_Application_Main_string__ + 160
31 BLE-test 0x000000010017c06c wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 156
32 BLE-test 0x0000000100202614 mono_jit_runtime_invoke (mini.c:6737)
33 BLE-test 0x000000010024d31c mono_runtime_invoke (object.c:2842)
34 BLE-test 0x00000001002513f8 mono_runtime_exec_main (object.c:4099)
35 BLE-test 0x00000001002afa34 xamarin_main (monotouch-main.m:400)
36 BLE-test 0x00000001001ca924 main + 92
37 libdyld.dylib 0x000000019511aa04 start + 0
</code></pre>
<h1>Observations and thoughts;</h1>
<p>If I remove the delegates to the peripheral after it has been connected, but before I try to discover its services (which means that I'll never see the result of the discovery, but just for test), the DiscoverService routine does NOT result in a crash;</p>
<pre><code>// CurrentPeripheral.DiscoveredService += (object sender, NSErrorEventArgs e) => ...
// CurrentPeripheral.DiscoveredCharacteristic += (object sender, ...
</code></pre>
<p>Likewise, I've also tried to keep the delegates above, but remove the actual call to <em>DiscoverServices</em> and that also work without crashing (which is again a stupid test perhaps, but I just wanted to rule-out that something happened when I assigned the delegates in the first place).</p>
<p>I've also read about other peoples experiences with these kind of issues/errors and someone said that it's a GC-issue where an object might be GC'd even though it's still referenced? </p>
<p>Someone also mentioned that things worked in Release-mode but not in debug mode -- so I've tested to run my app in release which ALSO seems to work -- but I don't have any UI so I can't guarantee that is actually works -- but I do know that it does <strong>not</strong> crash with SIGSEGV... </p>
<p>I'm confused. Please help me understand <em>why</em> Xamarin does not like me. I'm happy to adjust and play by the Xamarin-rules, as long as I understand the constraints and what I can/can't do. </p>
<h1>UPPDATE;</h1>
<p>I just tried to see if the error was the callback/event-handlers inside the
CBPeripheral, or the actual DiscoverServices method call. So I tried to call
the function and wait 500ms and then see if the services had been discovered in
my peripheral object;</p>
<pre><code>Console.WriteLine ("List of services (before discovery attempt)");
if (CurrentPeripheral.Services != null)
foreach (CBService service in CurrentPeripheral.Services) {
Console.WriteLine ("Service: " + service);
}
CurrentPeripheral.DiscoverServices();
await Task.Delay(500);
Console.WriteLine ("List of services (after discovery attempt)");
if (CurrentPeripheral.Services != null)
foreach (CBService service in CurrentPeripheral.Services) {
Console.WriteLine ("Service: " + service);
}
</code></pre>
<p>... and it works! Hence, this means that the call to DiscoverServices works
just fine, but the callbacks does not!</p>
| 3 | 5,891 |
Android external online database
|
<p>i have an online database in phpMyAdmin. At this time I can query him and I can get the result in a TextView but i want to get the value of each cell, how do I?</p>
<p>This is an example</p>
<pre><code>[{"Monday":"","Tuesday":"","Wednesday":"","Thursday":"","Friday":"","Saturday":"","Sunday":"","id":"","info":""},...]
</code></pre>
<p>I would like to get the value of Monday for example.</p>
<p>Thanks</p>
<p>code sendQuery.java:</p>
<pre><code> public class sendQuery {
/////////// Public method to send Query ///////////
public static String send(String query) {
String result = "0";
InputStream is = null;
String weekDayVal;
//the query to send
ArrayList<NameValuePair> querySend = new ArrayList<NameValuePair>();
querySend.add(new BasicNameValuePair("querySend",query));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://locali.altervista.org/php/locali.php");
httppost.setEntity(new UrlEncodedFormEntity(querySend));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(
new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
try{
JSONArray weekDetails = new JSONArray ( result); // Your response string
for(int index=0;index < weekDetails.length();index++)
{
JSONObject tempWeekDetail = weekDetails.getJSONObject(index);
weekDayVal = tempWeekDetail.getString("Monday");// Value for Monday
//added this Log which you can view from LogCat. also changed above variable name
Log.i("Resp Value"," Moday Value"+weekDayVal);
}
}catch(Exception e)
{
//catch exception here
}
}catch(Exception e){
Log.e("log_tag", "Error converting result: "+e.toString());
}
Log.i("SendQUERY", result);
return result;
}
</code></pre>
<p>}</p>
<p>main.java:</p>
<pre><code> public class main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView resLayout = (TextView) findViewById(R.id.res);
String res = sendQuery.send("SELECT * FROM contatti");
resLayout.append(res);
}
}
</code></pre>
| 3 | 1,126 |
VB.NET ActiveDocument.Hyperlink Command failed when adding hyperlinks
|
<p>When i try to add an hyperlink to the activedocument I get the exception "Command failed" every single time. I added <code>word.ActiveDocument.Hyperlinks.Add(Anchor:=word.Selection, Address:="www.google.com", TextToDisplay:="TEST")</code> to add an hyperlink to the existing document with an alias. But it doesn't seem to work and the exception, inner exception and stacktrace ar not of any help at all.</p>
<pre><code> Dim word As Microsoft.Office.Interop.Word.Application = CreateObject("Word.Application")
word.Documents.Add(documentProperty.Filename)
If Not IO.Directory.Exists(documentProperty.SaveAsFilename.Substring(0, documentProperty.SaveAsFilename.LastIndexOf("\"))) Then
IO.Directory.CreateDirectory(documentProperty.SaveAsFilename.Substring(0, documentProperty.SaveAsFilename.LastIndexOf("\")))
End If
word.Visible = False
word.PrintPreview = False
word.ScreenUpdating = False
word.ActiveDocument.Hyperlinks.Add(Anchor:=word.Selection, Address:="www.google.com", TextToDisplay:="TEST")
word.ActiveDocument.ExportAsFixedFormat(OutputFileName:=documentProperty.SaveAsFilename,
ExportFormat:=Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF,
OpenAfterExport:=False,
OptimizeFor:=Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint,
Range:=Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument,
From:=1,
To:=1,
Item:=Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent,
IncludeDocProps:=True,
KeepIRM:=True,
CreateBookmarks:=Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks,
DocStructureTags:=True,
BitmapMissingFonts:=True,
UseISO19005_1:=False)
</code></pre>
| 3 | 1,434 |
How to increment the value of a variable in a loop for insert sql statement using pyodbc
|
<p>I'm attempting to pull employee timecard data from an API and subsequently insert it into a sql database. I want the code to look at the data, isolate the punches in and out for a specific date and then insert them into the sql database. The only catch is that the database requires a sequence number "SEQ_NO" to indicate which punch of the day it was to account for breaks, lunches etc. so I want it to loop increasing the sequence number by 1 without executing the header insert more than once for the same employee(eventually "kelly walton" and "080098" will be replaced with variables so that this can execute for every employee in the data set.</p>
<p>I've tried just about every variable incrementation method I've found on stack overflow and I cannot get it to work. for loops, while loops if, elif statements you name it and I can't get anything to work. This is just one version of the code. To clarify the issue is that no matter which type of loop I try to use it tries to duplicate some of the values either the header query or the punch data resulting in errors in the sql database.</p>
<pre><code>today = ('2019-06-05')
with open('timepunches.json', 'r') as f:
timepunches_dict = json.load(f)
for punch in timepunches_dict:
punch_in = punch['PunchInDateTime']
punch_out = punch['PunchOutDateTime']
punch_in_sql = punch_in.replace('T', ' ')
punch_out_sql = punch_out.replace('T', ' ')
if today in punch_in_sql:
#print(punch_in_sql, punch_out_sql)
cnx = pyodbc.connect('driver={SQL Server};server=MY_server;database=my_db;uid=****;pwd=****')
cursor = cnx.cursor()
sequence_number = 1
if sequence_number == 1:
sql_insert_header_query = ''' INSERT INTO my_db.dbo.SY_TIMCRD_HDR
(STR_ID, USR_ID, TIMCRD_DAT, USR_NAM) VALUES ('M-MAC', '080098', '2019-06-05 00:00:00.000', 'Kelly Walton')'''
sql_timecard_data = '''INSERT INTO my_db.dbo.SY_TIMCRD_LIN
(STR_ID, USR_ID, TIMCRD_DAT, SEQ_NO, CLCK_IN_TIM) VALUES ('M-MAC', '080098', [dbo].[fnDateOnly]('%s'), '%s', [dbo].[fnTimeOnly]('%s'))'''
cursor.execute(sql_insert_header_query)
cursor.execute(sql_timecard_data % (today, sequence_number, punch_in_sql))
sequence_number+=1
elif sequence_number == 2:
sql_timecard_data = '''INSERT INTO my_db.dbo.SY_TIMCRD_LIN
(STR_ID, USR_ID, TIMCRD_DAT, SEQ_NO, CLCK_OUT_TIM) VALUES ('M-MAC', '080098', [dbo].[fnDateOnly]('%s'), '%s', [dbo].[fnTimeOnly]('%s'))'''
cursor.execute(sql_insert_header_query)
cursor.execute(sql_timecard_data % (today, sequence_number, punch_out_sql))
sequence_number+=1
cnx.commit()
cnx.close()
</code></pre>
<p>I thought this would increase 'sequence_number' to 2 and execute the next part. and I intended to add more statements once I got this part working.</p>
<p>Edit: This is the JSON data in 'timepunches.json' which may be helpful.</p>
<pre><code>[{"JobCodeId": null,
"PunchInApprovalStatusId": 4,
"PunchInImageUrl": "",
"LocationName": "",
"PunchInNotes": "",
"PunchOutLongitude": null,
"PunchOutLatitude": null,
"Employee":
{"Username": "starlord",
"EmployeeId":"080097",
"FirstName": "Peter",
"LastName": "Quill",
"ProfileMiniImageUrl": "https://buddypunchapp.blob.core.windows.net/profileminipics/new_employee_face2.jpg",
"Email": "starlord@email.com",
"FullName": "Peter Quill",
"Id": 346968,
"IsActive": true},
"PunchOutDateTime": "2019-06-10T10:00:00",
"BreakMinutes": 0,
"Hours": 2.0,
"PunchOutApprovalStatusName": "Changed By Manager",
"OverTimeHours": 0.0,
"DoubleTimeHours": 0.0,
"JobCodeName": "",
"PunchInIpAddress": "",
"PunchInApprovalStatusName": "Changed By Manager",
"PTOEarningCodeAbbr": "",
"PunchOutIpAddress": "",
"PunchOutImageUrl": "",
"PunchInLongitude": null,
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"PTOHours": null,
"PunchOutApprovalStatusId": 4,
"PunchInDateTime": "2019-06-10T08:00:00",
"PunchOutNotes": "",
"PTOEarningCodeId": null,
"Id": 12971600,
"PunchInLatitude": null,
"LocationId": null,
"Duration": "02:00:00",
"RegularHours": 2.0},
{"JobCodeId": null,
"PunchInApprovalStatusId": 4,
"PunchInImageUrl": "",
"LocationName": "",
"PunchInNotes": "",
"PunchOutLongitude": null,
"PunchOutLatitude": null,
"Employee": {
"Username": "starlord",
"EmployeeId": "080097",
"FirstName": "Peter",
"LastName": "Quill",
"ProfileMiniImageUrl": "https://buddypunchapp.blob.core.windows.net/profileminipics/new_employee_face2.jpg",
"Email": "starlord@email.com",
"FullName": "Peter Quill",
"Id": 346968,
"IsActive": true},
"PunchOutDateTime": "2019-06-10T12:00:00",
"BreakMinutes": 0,
"Hours": 1.75,
"PunchOutApprovalStatusName": "Changed By Manager",
"OverTimeHours": 0.0,
"DoubleTimeHours": 0.0,
"JobCodeName": "",
"PunchInIpAddress": "",
"PunchInApprovalStatusName": "Changed By Manager",
"PTOEarningCodeAbbr": "",
"PunchOutIpAddress": ",
"PunchOutImageUrl": "",
"PunchInLongitude": null,
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"PTOHours": null,
"PunchOutApprovalStatusId": 4,
"PunchInDateTime": "2019-06-10T10:15:00",
"PunchOutNotes": "",
"PTOEarningCodeId": null,
"Id": 12971609,
"PunchInLatitude": null,
"LocationId": null,
"Duration": "01:45:00",
"RegularHours": 1.75},
{"JobCodeId": null,
"PunchInApprovalStatusId": 4,
"PunchInImageUrl": "",
"LocationName": "",
"PunchInNotes": "",
"PunchOutLongitude": null,
"PunchOutLatitude": null,
"Employee": {
"Username": "starlord",
"EmployeeId": "080097",
"FirstName": "Peter",
"LastName": "Quill",
"ProfileMiniImageUrl": "https://buddypunchapp.blob.core.windows.net/profileminipics/new_employee_face2.jpg",
"Email": "starlord@email.com",
"FullName": "Peter Quill",
"Id": 346968,
"IsActive": true},
"PunchOutDateTime": "2019-06-10T15:00:00",
"BreakMinutes": 0,
"Hours": 2.0,
"PunchOutApprovalStatusName": "Changed By Manager",
"OverTimeHours": 0.0,
"DoubleTimeHours": 0.0,
"JobCodeName": "",
"PunchInIpAddress": "",
"PunchInApprovalStatusName": "Changed By Manager",
"PTOEarningCodeAbbr": "",
"PunchOutIpAddress": "",
"PunchOutImageUrl": "",
"PunchInLongitude": null,
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"PTOHours": null,
"PunchOutApprovalStatusId": 4,
"PunchInDateTime": "2019-06-10T13:00:00",
"PunchOutNotes": "",
"PTOEarningCodeId": null,
"Id": 12971618,
"PunchInLatitude": null,
"LocationId": null,
"Duration": "02:00:00",
"RegularHours": 2.0},
{"JobCodeId": null,
"PunchInApprovalStatusId": 4,
"PunchInImageUrl": "",
"LocationName": "",
"PunchInNotes": "",
"PunchOutLongitude": null,
"PunchOutLatitude": null,
"Employee": {
"Username": "starlord",
"EmployeeId": "080097",
"FirstName": "Peter",
"LastName": "Quill",
"ProfileMiniImageUrl": "https://buddypunchapp.blob.core.windows.net/profileminipics/new_employee_face2.jpg",
"Email": "starlord@email.com",
"FullName": "Peter Quill",
"Id": 346968,
"IsActive": true},
"PunchOutDateTime": "2019-06-10T17:00:00",
"BreakMinutes": 0,
"Hours": 1.75,
"PunchOutApprovalStatusName": "Changed By Manager",
"OverTimeHours": 0.0,
"DoubleTimeHours": 0.0,
"JobCodeName": "",
"PunchInIpAddress": "",
"PunchInApprovalStatusName": "Changed By Manager",
"PTOEarningCodeAbbr": "",
"PunchOutIpAddress": "",
"PunchOutImageUrl": "",
"PunchInLongitude": null,
"BreakApprovalStatusId": null,
"BreakApprovalStatusName": null,
"PTOHours": null,
"PunchOutApprovalStatusId": 4,
"PunchInDateTime": "2019-06-10T15:15:00",
"PunchOutNotes": "",
"PTOEarningCodeId": null,
"Id": 12971630,
"PunchInLatitude": null,
"LocationId": null,
"Duration": "01:45:00",
"RegularHours": 1.75}]
</code></pre>
| 3 | 3,939 |
FilteredRowSet filters not applying cumulatively
|
<p>I am trying to filter data from my database, which consists of NHL game statistics. I want to create a FilteredRowSet which holds all of the games between two specific teams. I have filters to do so, but the filters will not apply cumulatively. When I apply the second filter, it cancels out the first one. </p>
<p>I have tried implementing many different kinds of filters but I always run into an issue because the teams can be in one of two columns. I can not figure out a way to check whether both columns satisfy what I am looking for. </p>
<p>This is the filter I am using</p>
<p>public class TeamFilter implements Predicate {</p>
<pre><code>private int lo;
private int hi;
private String colName = null;
private int colNumber = -1;
public TeamFilter(int lo, int hi, int colNumber) {
this.lo = lo;
this.hi = hi;
this.colNumber = colNumber;
}
public TeamFilter(int lo, int hi, String colName) {
this.lo = lo;
this.hi = hi;
this.colName = colName;
}
@Override
public boolean evaluate(Object value, String columnName) {
boolean evaluation = true;
if (columnName.equalsIgnoreCase(this.colName)) {
int columnValue = ((Integer) value).intValue();
if ((columnValue == this.lo) || (columnValue == this.hi)) {
evaluation = true;
} else {
evaluation = false;
}
}
return evaluation;
}
@Override
public boolean evaluate(Object value, int columnNumber) {
boolean evaluation = true;
if (this.colNumber == columnNumber) {
int columnValue = ((Integer) value).intValue();
if ((columnValue == this.lo) || (columnValue == this.hi)) {
evaluation = true;
} else {
evaluation = false;
}
}
return evaluation;
}
@Override
public boolean evaluate(RowSet rs) {
CachedRowSet frs = (CachedRowSet) rs;
boolean evaluation = false;
try {
int columnValue = -1;
if (this.colNumber > 0) {
columnValue = frs.getInt(this.colNumber);
} else if (this.colName != null) {
columnValue = frs.getInt(this.colName);
} else {
return false;
}
if ((columnValue == this.lo) || (columnValue == this.hi)) {
evaluation = true;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (NullPointerException npe) {
System.err.println("NullPointerException caught");
return false;
}
return evaluation;
}
</code></pre>
<p>}</p>
<p>This is how I am implementing the filters on to my FilteredRowSet</p>
<pre><code>TeamFilter fltr1 = new TeamFilter(homeID, awayID, 4);
TeamFilter fltr4 = new TeamFilter(homeID, awayID, 5);
FilteredRowSet trs = new FilteredRowSetImpl();
trs.setCommand("SELECT * FROM GAMES");
trs.setUsername("root");
trs.setPassword("rootpass");
trs.setUrl("jdbc:mysql://localhost:3306/" + "testData"
+ "?useUnicode=true&useJD"
+ "BCCompliantTimezoneShift=true&useLegacyDatetimeCode=fal"
+ "se&serverTimezone=EST");
trs.execute();
// filters the rowset
trs.beforeFirst();
trs.setFilter(fltr1);
while (trs.next()) {
System.out.println((long) trs.getDouble("GAMENUMBER") + ", "
+ trs.getString("HomeTeam") + ", "
+ trs.getString("AwayTeam") + ", "
+ trs.getInt("homeID") + ", " + trs.getInt("awayID"));
}
System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
trs.beforeFirst();
trs.setFilter(fltr4);
while (trs.next()) {
System.out.println((long) trs.getDouble("GAMENUMBER") + ", "
+ trs.getString("HomeTeam") + ", "
+ trs.getString("AwayTeam") + ", "
+ trs.getInt("homeID") + ", " + trs.getInt("awayID"));
}
trs.beforeFirst();
</code></pre>
<p>and this is what I get before and after the second filter. </p>
<p><a href="https://i.stack.imgur.com/HSPln.png" rel="nofollow noreferrer">Output of the FilteredRowSet before and after second filter</a>
The first filter filters the home team and the second filter filters the away team. The teams I am looking to find are the New York Rangers and the Dallas Stars. As you can see, once I do the second filter, only games where the away team is one of those two shows up. The first filter is only when the home team is one of those two teams. The filters will not apply cumulatively, even though that is what the oracle docs say will happen. What am I missing?</p>
| 3 | 2,023 |
Dask: Where do SSHCluster workers log to? (KilledWorker exception)
|
<p>I wrote a little starter script for dask <code>SSHCluster</code> and <code>LocalCluster</code> which works great (see below). </p>
<p>But when I let it run and a worker crashes with the </p>
<p><code>KilledWorker: ("('from-delayed-pandas_read_text-read-block-head-1-1-from-delayed-f0f78ffea007aeeccc7a9e04880d0195', 0)", <Worker 'tcp://192.168.56.11:34965', name: 0, memory: 0, processing: 1>)</code></p>
<p>exception, I wonder where I can find the <strong>crash logs</strong> / <strong>tracebacks</strong> of the remote workers? Is there a way to collect them centerally on the Scheduler Host? Or are there some logs on the remote machines?</p>
<p>The <a href="https://stackoverflow.com/questions/46691675/what-do-killedworker-exceptions-mean-in-dask">existing answer</a> only states, that it is logging to <code>stdout</code> - But I can not find any logs there as well..</p>
<pre><code>from dask.distributed import Client, LocalCluster, SSHCluster
import time, datetime
import pandas as pd
import numpy as np
import os, sys
from collections import Counter
# Add Home Folder of CGi to path
os.environ["HOME"] = "/home/cgi/"
os.path.expanduser("~/.ssh/id_rsa")
#os.path.expanduser('/home/cgi/')
#os.path.expandvars('/home/cgi/')
def run_cluster(local=0, HOST = '10.8.0.1', SCHEDULER_PORT = 8711, DASHBOARD_PORT=8710,
DASK_WORKER_PROCESSES = 16, NTHREADS=2, SILENCE_LOGS = 0):
start_msg = "Starting a "
if local: start_msg += "local"
else: start_msg += "ssh"
start_msg += " dask cluster. SCHEDULER_PORT=%s and DASHBOARD_PORT=%s." % ( SCHEDULER_PORT, DASHBOARD_PORT )
print(start_msg)
dashboard_address = ':%s' % DASHBOARD_PORT
if local:
cluster = LocalCluster(dashboard_address=dashboard_address, scheduler_port=SCHEDULER_PORT,
n_workers=DASK_WORKER_PROCESSES, host=HOST, silence_logs=SILENCE_LOGS)
else:
worker_hosts = [
"localhost", "localhost", "localhost", "localhost",
"192.168.56.11","192.168.56.11","192.168.56.11","192.168.56.11",
"192.168.56.11","192.168.56.11","192.168.56.11","192.168.56.11",
"192.168.56.11","192.168.56.11","192.168.56.11","192.168.56.11",
"192.168.56.11","192.168.56.11","192.168.56.11","192.168.56.11",
"192.168.56.11","192.168.56.11","192.168.56.11","192.168.56.11"
]
print("Starting a DASK SSHCluster with (%s) workers on %s different hosts... "
% len(worker_hosts), len(set(worker_hosts)))
cluster = SSHCluster(
worker_hosts,
connect_options = {"known_hosts": None},
worker_options = {"nthreads": NTHREADS},
scheduler_options={"port": SCHEDULER_PORT, "dashboard_address": dashboard_address}
)
print("SSHCLUSTER>%s" % cluster)
print("DASK Cluster Dashboard = http://%s%s/status" % (HOST, dashboard_address))
#cluster.scale(3)
client = Client(cluster)
#print(cluster)
print(client)
print("Press Enter to quit ...")
while (not time.sleep(5)):
continue
time.sleep(0.1)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Webserver which runs the dash/plotly dashboard(s). Name: BT_HISTORY')
parser.add_argument('-l', '--local-cluster', help='1/0', required=False, default=1)
parser.add_argument('-q', '--quiet', help='1/0', required=False, default=False)
parser.add_argument('-dp', '--dashboard-port', help='port to run dashboard (default=%s)' % 8710, default=8710, required=False)
parser.add_argument('-sp', '--scheduler-port', help='port to run scheduler (default=%s)' % 8711, default=8711, required=False)
args = vars(parser.parse_args())
print("args>%s" % args)
LOCAL = int(args['local_cluster'])
DASHBOARD_PORT = int(args['dashboard_port'])
SCHEDULER_PORT = int(args['scheduler_port'])
SILENCE_LOGS = int(args['quiet'])
run_cluster(local=LOCAL, DASHBOARD_PORT=DASHBOARD_PORT, SCHEDULER_PORT=SCHEDULER_PORT, SILENCE_LOGS=SILENCE_LOGS)
</code></pre>
| 3 | 1,768 |
Authentication in ASP.NET MVC
|
<p>I begin with ASP.NET and I have a problem with authentication.</p>
<p>This is the code:</p>
<p>web.config </p>
<pre class="lang-xml prettyprint-override"><code><system.web>
<authentication mode="Forms">
<forms loginUrl="~/users/login" timeout="3000" />
</authentication>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
</code></pre>
<p>login</p>
<pre class="lang-cs prettyprint-override"><code>public ActionResult login()
{
if (Request.HttpMethod == "POST")
{
if (Request.Form["email"] == null || Request.Form["password"] == null)
ViewData["error"] = "form_error";
else
{
User user = this.dal.authUser(
Request.Form["email"],
Request.Form["password"]);
if (user == null)
ViewData["error"] = "auth_error";
else
{
FormsAuthentication.SetAuthCookie(user.id.ToString(), false);
return Redirect("/profiles/" + user.id);
}
}
}
return (View());
}
</code></pre>
<p>profile controller</p>
<pre class="lang-cs prettyprint-override"><code>[HttpGet]
public ActionResult get(int id)
{
ViewData["auth"] = false;
if (HttpContext.User.Identity.IsAuthenticated)
ViewData["auth"] = true;
Response.Write(HttpContext.User.Identity.Name);
Profile profile = this.dal.getProfile(id);
if (profile == null)
return View("~/Views/error404.cshtml");
ViewData["profile"] = profile;
return View();
}
</code></pre>
<p>and View for get a profile</p>
<pre><code>@using Plume.Areas.Users.Models;
@{
Layout = "~/Views/Layout/layout.cshtml";
Variables.pageTitle = "Profil";
Profile profile = (Profile)ViewData["profile"];
bool auth = (bool)ViewData["auth"];
}
@{
if (auth)
{
<h1>Auth</h1>
}
}
<p>
ceci est le profil de :
@profile.username
<br />
dont l'email est :
@profile.user.email
</p>
</code></pre>
<p>So, when I log, a cookie called <code>.ASPXAUTH</code> is returned, but in the view for a profile, the <code>h1</code> isn't displayed.</p>
<p>What is not correct?</p>
| 3 | 1,029 |
Running Spring Hibernate Project in Tomcat as Standalone and Embedded Tomcat in STS IDE
|
<p>I have an issue when i run my application as a standalone web application using Tomcat. </p>
<p>I use spring , struts 2 and hibernate . </p>
<p>The weird part is when i run the application from the embedded tomcat in my STS IDE it is running fine.</p>
<p>In both scenarios the web application runs fine but certain hibernate models are not getting initialized causing certain screens to fail when the application is run in the stand alone mode.</p>
<p>Any help/direction would be greatly appreciated.</p>
<p>Below is the exact error:</p>
<p>Error in Pre-loading models or ppa_ids
org.springframework.orm.hibernate3.HibernateQueryException: RealTimeModel is not mapped [select distinct forecast_model from RealTimeModel]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: RealTimeModel is not mapped [select distinct forecast_model from RealTimeModel]
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:656)</p>
<p>applicationContext.xml </p>
<pre><code><beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- MyBatis setup start -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="txProxyTemplate" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="permissionMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.guzmanenergy.dal.PermissionMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="roleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.guzmanenergy.dal.RoleMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.guzmanenergy.dal.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="authorityMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.guzmanenergy.dal.AuthorityMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="permissionService" class="com.guzmanenergy.service.impl.PermissionServiceImpl">
<property name="permissionMapper" ref="permissionMapper"></property>
</bean>
<bean id="authorityService" class="com.guzmanenergy.service.impl.AuthorityServiceImpl">
<property name="authorityMapper" ref="authorityMapper"></property>
</bean>
<bean id="userServiceTarget" class="com.guzmanenergy.service.impl.UserServiceImpl">
<property name="usermapper" ref="userMapper"></property>
</bean>
<bean id="userService" parent="txProxyTemplate">
<property name="target" ref="userServiceTarget"></property>
</bean>
<!-- MyBatis setup stop -->
<!-- email setup start -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<!-- 25, 465, 587 -->
<property name="username" value="support@getrident.com" />
<property name="password" value="Aragon101!" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<!-- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> -->
<!-- <property name="host" value="smtp.gmail.com" /> -->
<!-- <property name="port" value="587" /> 25, 465, 587 -->
<!-- <property name="username" value="GPMreporting@gmail.com" /> -->
<!-- <property name="password" value="Guzman1234" /> -->
<!-- <property name="javaMailProperties"> -->
<!-- <props> -->
<!-- <prop key="mail.smtp.auth">true</prop> -->
<!-- <prop key="mail.smtp.starttls.enable">true</prop> -->
<!-- </props> -->
<!-- </property> -->
<!-- </bean> -->
<bean id="resetPasswordMailer" class="com.guzmanenergy.util.ResetPasswordMailer">
<property name="mailSender" ref="mailSender" />
</bean>
<bean id="sendEmail" class="com.guzmanenergy.util.SendMail">
<property name="mailSender" ref="mailSender" />
</bean>
<!-- email setup stop -->
<!-- Spring + Hibernate Configuration -->
<import resource="applicationContext-hibernate.xml"/>
<!-- Curve Action Beans -->
<bean id="curveDao" class="com.guzmanenergy.action.dao.Impl.CurveDaoImpl" scope="prototype">
<property name="sessionFactory">
<ref bean="Hibernate_sessionFactory"/>
</property>
</bean>
<bean id="curveService" class="com.guzmanenergy.action.service.Impl.CurveServiceImpl" scope="prototype">
<property name="curveDao">
<ref bean="curveDao"/>
</property>
</bean>
<bean id="curveAction" class="com.guzmanenergy.action.CurveAction_s2sh" scope="prototype">
<property name="curveService">
<ref bean="curveService"/>
</property>
</bean>
<!-- Curve Action Beans End -->
<!-- Beans for physical_longterm_main -->
<bean id="physicalLongtermMainDao" class="com.guzmanenergy.action.dao.Impl.PhysicalLongtermMainDaoImpl" scope="prototype">
<property name="sessionFactory">
<ref bean="Hibernate_sessionFactory"/>
</property>
</bean>
<!-- Beans for physical_longterm_main End-->
<!-- Real Time Model Beans -->
<bean id="realTimeModelDao" class="com.guzmanenergy.action.dao.Impl.RealTimeModelDaoImpl" scope="prototype">
<property name="sessionFactory">
<ref bean="Hibernate_sessionFactory"/>
</property>
</bean>
<bean id="realTimeModelService" class="com.guzmanenergy.action.service.Impl.RealTimeModelServiceImpl" scope="prototype">
<property name="realTimeModelDao">
<ref bean="realTimeModelDao"/>
</property>
<property name="physicalLongtermMainDao">
<ref bean="physicalLongtermMainDao"/>
</property>
</bean>
<bean id="RealTimeModelAction" class="com.guzmanenergy.action.RealTime_Model_Action" scope="prototype">
<property name="realTimeModelService">
<ref bean="realTimeModelService"/>
</property>
</bean>
<!-- Real Time Model Beans -->
<!-- forecast model download -->
<bean id="ForcastModelDownloadAction" class="com.guzmanenergy.action.ForcastModelDownloadAction" scope="prototype">
<property name="realTimeModelService">
<ref bean="realTimeModelService"/>
</property>
</bean>
<!-- forecast model download -->
<!-- Spring + Hibernate Configuration End -->
</code></pre>
<p></p>
<p>applicationContext-hibernate.xml</p>
<pre><code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" id="ETRM_database">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<!--
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
-->
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="Hibernate_sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingDirectoryLocations">
<list>
<value>classpath:com/guzmanenergy/action/domain</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">/ehcache.xml</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="generate_statistics">true</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</prop>
</props>
</property>
<!--
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
-->
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" scope="prototype">
<property name="sessionFactory">
<ref bean="Hibernate_sessionFactory"/>
</property>
</bean>
<tx:advice id="ETRM_tx" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" read-only="false"/>
<tx:method name="update*" read-only="false"/>
<tx:method name="delete*" read-only="false"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.guzmanenergy.action.service.Impl.*.*(..))" id="ETRM_perform"/>
<aop:advisor advice-ref="ETRM_tx" pointcut-ref="ETRM_perform"/>
</aop:config>
</code></pre>
<p></p>
| 3 | 5,898 |
Need help in the following to reduce the execution time
|
<p>This is just a part of the code, it takes around 5 min for each iteration ( for a single el) to execute. </p>
<p>The length of fieldvalues is in the order of 1e6. I believe that multiple appends are eating away the time, Is there any alternative way for this ?</p>
<pre><code> PK2=[]
E_pl=[]
E_tot=[]
for k in range(103,109):
PK2_k=[]
E_pl_k=[]
E_tot_k=[]
b=frame.fieldOutputs['SDV'+str(k)]
fieldValues=b.values
for v in fieldValues:
PK2_k.append(v.data)
PK2.append(PK2_k)
b=frame.fieldOutputs['SDV'+str(k+6)]
fieldValues=b.values
for v in fieldValues:
E_tot_k.append(v.data)
E_tot.append(E_tot_k)
b=frame.fieldOutputs['SDV'+str(k+12)]
fieldValues=b.values
for v in fieldValues:
E_pl_k.append(v.data)
E_pl.append(E_pl_k)
t3=time.time()
print stepName,"All PK,E terms written",t3-at,"Sec"
PK2=np.array(PK2)
PK2=np.transpose(PK2)
E_tot=np.array(E_tot)
E_tot=np.transpose(E_tot)
E_pl=np.array(E_pl)
E_pl=np.transpose(E_pl)
</code></pre>
<p>Thanks in Advance !</p>
| 3 | 1,042 |
How to pass a generic interface to a method where it is reified?
|
<p>I have a generic interface</p>
<pre><code>public interface MyInterface<T> {
T method(T input);
}
</code></pre>
<p>and a couple of implementations of it, via ordinary classes like</p>
<pre><code>public class MyClass<T> implements MyInterface<T> {
@Override
public T method(T input) {
T output = input; // whatever
return output;
}
}
</code></pre>
<p>and anonymous classes (see below). Now I want to test these implementations:</p>
<pre><code>class TestClass1 {
// ...
}
class TestClass2 {
final int n;
final String s;
TestClass2(int n, String s) {
this.n = n;
this.s = s;
}
// ...
}
public class TestGenericImplementation {
private static <T> void makeTest(T testObject, MyInterface<T> impl) {
T output = impl.method(testObject);
if (output == null)
throw new NullPointerException();
// verify output further
}
// Question 1. How to specify the parameter here properly?
public static void testImplementation(MyInterface impl) {
// Question 2. How to avoid compiler warning about unchecked cast below?
// Doesn't work if impl is of type MyInterface<?> above
makeTest(new TestClass1(), impl);
makeTest(new TestClass2(1, "ABC"), impl);
// Ugly typecasts. Compiler complains.
makeTest(new TestClass1(), (MyInterface<TestClass1>) impl);
makeTest(new TestClass2(1, "ABC"), (MyInterface<TestClass2>) impl);
}
public static void main(String[] args) {
// Question 3. How to pass the interface argument here?
// Works but issues compiler warning about raw type
testImplementation(new MyClass());
testImplementation(new MyInterface() {
@Override
public Object method(Object input) {
return null; // whatever
}
});
// Looks ugly
testImplementation(new MyClass<Object>());
testImplementation(new MyInterface<Object>() {
@Override
public Object method(Object input) {
return null;
}
});
/* Diamond operator appeared only in Java 7,
* while generics were introduced in Java 5.
* What was the recommended way to solve this problem between 2004 and 2011?
* Besides that, this doesn't work for anonymous classes.
*/
testImplementation(new MyClass<>());
testImplementation(new MyInterface<>() { // Doesn't work
@Override
public Object method(Object input) {
return null;
}
});
testImplementation(x -> x); // Lambda exprssions are for simple cases only
}
}
</code></pre>
<p>The problem is that compiler is issuing a series of errors and warnings due to transition from a generic interface to its reified versions (those I need to use with the concrete classes <code>TestClass1</code> and <code>TestClass2</code> in place of the generic type variable <code>T</code>). Is it possible to avoid these warnings completely? If not (i.e. if they can only be suppressed), are there any pitfalls arising from this?</p>
| 3 | 1,279 |
retrieve repeateritem via jquery
|
<p>I want to retrieve the repeateritem via jquery to my saveorder function on codebehind</p>
<p>This is my jquery code:</p>
<pre><code> function saveOrder(controlid) {
var id = controlid.name.replace("$btnSave", "");
console.log(id)
$.ajax({
type: "POST",
url: '/mobile/Default.aspx/saveOrder',
data: '{par:"' + id + '"}',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data.d);
},
failure: function (response) {
console.log(response.d);
alert(response.d);
}
});
}
</code></pre>
<p>This is my codebehind code:</p>
<pre><code> [WebMethod]
public static void saveOrder(string par)
{
mobile_Menu m = new mobile_Menu();
RepeaterItem row = (RepeaterItem)m.FindControl(par);
RadioButtonList rdblExtraSauce = (RadioButtonList)row.FindControl("rdblExtraSauce");
CheckBoxList chkExtras = (CheckBoxList)row.FindControl("chkExtras");
CheckBoxList chklExtraDrink = (CheckBoxList)row.FindControl("chklExtraDrink");
RadioButtonList rdblExtraOption = (RadioButtonList)row.FindControl("rdblExtraOption");
RadioButtonList rdblSauce = (RadioButtonList)row.FindControl("rdblSauce");
CheckBoxList chkGarnish = (CheckBoxList)row.FindControl("chkGarnish");
List<ListItem> emptyList = new List<ListItem>();
HiddenField hfProductId = (HiddenField)row.FindControl("hfProductId");
string rdlPriceId = ((RadioButtonList)row.FindControl("rdblSize")).SelectedValue.Split(',')[0];
HiddenField hfMainProductId = (HiddenField)row.FindControl("hfMainProductId");
//Get previous values
if (m.Session["Cart"] != null)
{
m.values = (List<Order>)m.Session["Cart"];
}
if (chklExtraDrink.Items.Count > 0)
{
foreach (ListItem item in chklExtraDrink.Items)
if (item.Selected) m.values.Add(new Order(item.Value.Split(',')[0], item.Value.Split(',')[1], emptyList, 1));
}
if (rdblExtraSauce.Items.Count > 0)
{
if (rdblExtraSauce.SelectedValue != "Geen saus")
{
m.values.Add(new Order(rdblExtraSauce.SelectedValue.Split(',')[0], rdblExtraSauce.SelectedValue.Split(',')[1], emptyList, 1));
}
}
switch (Convert.ToInt32(hfMainProductId.Value))
{
case 16:
m.values.Add(new Order(hfProductId.Value, rdlPriceId, m.addMultiChoice(chkGarnish), 1));
break;
case 17:
//values.Add(new Order(hfProductId.Value, rdlPrice, rdblSauce.SelectedItem, addMultiChoice(chkExtras), 1)); ;
m.values.Add(new Order(hfProductId.Value, rdlPriceId, rdblSauce.SelectedItem, m.addMultiChoice(chkExtras), 1, rdblExtraOption.SelectedItem));
break;
case 19:
m.values.Add(new Order(hfProductId.Value, rdlPriceId, rdblSauce.SelectedItem, m.addMultiChoice(chkExtras), 1));
break;
case 20:
m.values.Add(new Order(hfProductId.Value, rdlPriceId, rdblSauce.SelectedItem, m.addMultiChoice(chkExtras), 1)); ;
break;
case 21:
m.values.Add(new Order(hfProductId.Value, rdlPriceId, rdblSauce.SelectedItem, 1));
break;
case 22:
m.values.Add(new Order(hfProductId.Value, rdlPriceId, rdblSauce.SelectedItem, m.addMultiChoice(chkExtras), 1));
break;
default:
m.values.Add(new Order(hfProductId.Value, rdlPriceId, m.addMultiChoice(chkGarnish), 1));
break;
}
//Save updated list
m.Session["Cart"] = m.values;
if (m.Session["Cart"] != null)
{
m.btnOrder.Text = "Winkelmandje (€ " + Global.CalcTotPrice(m.values) + ")";
}
}
</code></pre>
<p>I am not sure if I am doing it the right way, I am also new with jquery.
With this code I am getting an NullReferenceException. The uniqueID of the repeaterItem is passed succesfully via the parameter but the conversion to RepeaterItem fails.</p>
<p>more info: I have a nested Repeater (in total 2), where I want the RepeaterItem of the second Repeater</p>
| 3 | 2,012 |
Compiler trying to instantiate std::vector<double const> for no obvious reason
|
<p>This one has me baffled.</p>
<p>Here's the sample code in its entirety:</p>
<hr>
<pre><code>#include <vector>
struct Unit {};
template <typename DataType>
class Vector : public std::vector<DataType>
{
public:
typedef std::vector<DataType> base_t;
Vector() = default;
explicit Vector(Unit const &units);
bool check_class_invariant() const noexcept
{
return base_t::size() < 2;
}
operator Vector<DataType const>() const;
private:
Unit units_;
};
void foo()
{
Vector<double> a;
Vector<double> b(a); // wants to construct Vector<double const> for some reason
}
</code></pre>
<hr>
<p>This is a much boiled down version of code that actually does something interesting.</p>
<p>Compilation fails with g++ 8.1.0. The error messages indicate that the compiler is trying to instantiate <code>Vector<double const></code> at the indicated line, which implies instantiating <code>std::vector<double const></code>, which is forbidden by the standard.</p>
<p>Here's the full error message:</p>
<pre><code>In file included from /scratch/vendors/spack.20180425/opt/spack/linux-rhel7-x86_64/gcc-4.8.5/gcc-8.1.0-3c5hjkqndywdp3w2l5vts62xlllrsbtq/include/c++/8.1.0/vector:64,
from /home/kgbudge/src/core/src/utils/test/test.cc:1:
/scratch/vendors/spack.20180425/opt/spack/linux-rhel7-x86_64/gcc-4.8.5/gcc-8.1.0-3c5hjkqndywdp3w2l5vts62xlllrsbtq/include/c++/8.1.0/bits/stl_vector.h: In instantiation of âclass std::vector<const double, std::allocator<const double> >â:
/home/kgbudge/src/core/src/utils/test/test.cc:6:7: required from âclass Vector<const double>â
/home/kgbudge/src/core/src/utils/test/test.cc:30:23: required from here
/scratch/vendors/spack.20180425/opt/spack/linux-rhel7-x86_64/gcc-4.8.5/gcc-8.1.0-3c5hjkqndywdp3w2l5vts62xlllrsbtq/include/c++/8.1.0/bits/stl_vector.h:351:21: error: static assertion failed: std::vector must have a non-const, non-volatile value_type
static_assert(is_same<typename remove_cv<_Tp>::type, _Tp>::value,
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/scratch/vendors/spack.20180425/opt/spack/linux-rhel7-x86_64/gcc-4.8.5/gcc-8.1.0-3c5hjkqndywdp3w2l5vts62xlllrsbtq/include/c++/8.1.0/bits/stl_vector.h:354:21: error: static assertion failed: std::vector must have the same value_type as its allocator
static_assert(is_same<typename _Alloc::value_type, _Tp>::value,
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
make[2]: *** [src/utils/test/CMakeFiles/Ut_utils_test_exe.dir/test.cc.o] Error 1
make[1]: *** [src/utils/test/CMakeFiles/Ut_utils_test_exe.dir/all] Error 2
</code></pre>
<p>Why is the compiler trying to instantiate <code>Vector<double const></code>?</p>
<p>Clues: If I change the <code>units_</code> member from <code>struct Unit</code> to <code>int</code>, the code compiles.</p>
<p>If I remove either the constructor taking a single <code>struct Unit</code> argument, or the conversion operator to <code>Vector<DataType const></code>, the code compiles.</p>
<p>Any ideas what is happening here? </p>
<p>(edit: My question is not why std::vector cannot be instantiated for double const. It is why the compiler is trying to instantiate std::vector in the first place.)</p>
<p>(Further edit: See the comments for an explanation of the context for this question.</p>
<p>It looks like this may solve my problem:</p>
<pre><code>
struct Unit
{
};
template <typename DataType> class Vector;
template <typename DataType> class Vector<DataType const>;
template <typename DataType> class Vector : public std::vector<DataType>
{
public:
typedef std::vector<DataType> base_t;
Vector() = default;
// explicit Vector(Unit const &units);
bool check_class_invariant() const noexcept { return base_t::size() < 2; }
operator Vector<DataType const>() const;
private:
Unit units_;
};
void foo()
{
Vector<double> a;
Vector<double> b(a); // wants to construct Vector<double const>
}
</code></pre>
<p>The code now builds, because presumably no attempt is made to instantiate <code>operator Vector<double const></code> if it is unused and if <code>Vector<double const></code> is declared as a specialization but not (yet) defined.</p>
<p>I'm not sure how reliable this is, though.)</p>
<p>(Further further edit: No, not reliable. The translation system is determined to try to instantiate <code>Vector<double const></code> if <code>Vector<double const></code> appears as a completed type anywhere in the <code>Vector<double></code> interface, whether I intend to use that part of the interface or not.</p>
<p>And to close this discussion: The context is that <code>Vector</code> was originally written to use a different underlying container than <code>std::vector</code>, and it worked fine since that container supported <code>const</code> element types. I was tasked to try to extend this to work with <code>std::vector</code> as the underlying container. Having an <code>operator Vector<Database double></code> was a necessary requirement for the original underlying container type, which I must still support, and I can't discard it. So the answer is that I can't extend this to <code>std::vector</code> as the underlying container.</p>
<p>Unless my team decides I should write a specialization just for <code>std::vector</code>. <em>Sigh</em>)</p>
| 3 | 2,058 |
Fill a table with elements from another table
|
<p>I've a problem with my java project. I have two text files to insert in postgresql with the jdbc driver. the two files are of this type:
1) snp (rsid, chr, boolean value)
2) locus (rsid, mrna, gene, class)</p>
<p>I have to get two tables of this type:
1)Snp (id serial, rsid varchar, chr varchar, has_sig boolean)
2)Locus (id serial, mana_acc varchar, gene varchar, class varchar, snp_id integer)
where snp_id of locus is foreign key references to Snp(id).</p>
<p>The field I can use for joining between tables is rsid which is common to both files.</p>
<p>I've created the table in this way:</p>
<pre><code>st = connection.prepareStatement(
"CREATE TABLE IF NOT EXISTS snp ("
+ "id SERIAL PRIMARY KEY, "
+ "rsid varchar(100), "
+ "chr varchar(100), "
+ "has_sig varchar(100))");
st.executeUpdate();
st.close();
st = connection.prepareStatement(
"CREATE TABLE IF NOT EXISTS locus ("
+ "id SERIAL PRIMARY KEY, "
+ "rsid varchar(100), "
+ "mrna_acc varchar(100), "
+ "gene varchar(100), "
+ "class varchar(100), "
+ "snp_id integer REFERENCES snp(id) on delete cascade on update cascade)");
st.executeUpdate();
st.close();
</code></pre>
<p>Then I put the files in the tables using the select query instead of the snp_id field:</p>
<pre><code>FileSnp fs = new FileSnp("/Users/valentinafratini/Documents/Progetto Tesi/FactoryMethodDb/snp.csv");
fs.readFile();
while (fs.line!=null) {
fs.line = fs.reader.readLine();
if (fs.line!=null && fs.line.length()>0) {
fs.obj = fs.line.split("\\s+");
fs.readSingleObj();
st = connection.prepareStatement("INSERT INTO snp ("
+ "id, "
+ "rsid, "
+ "chr, "
+ "has_sig) "
+ "VALUES (DEFAULT, ?, ?, ?)");
st.setString(1, fs.rsid);
st.setString(2, fs.chr);
st.setString(3, fs.has_sig);
st.executeUpdate();
st.close();
FileLocus fl = new FileLocus("/Users/valentinafratini/Documents/Progetto Tesi/FactoryMethodDb/locus.csv");
fl.readFile();
while (fl.line!=null) {
fl.line = fl.reader.readLine();
if (fl.line!=null && fl.line.length()>0) {
fl.obj = fl.line.split("\\s+");
fl.readSingleObj();
st = connection.prepareStatement("INSERT INTO locus ("
+ "id, "
+ "rsid, "
+ "mrna_acc, "
+ "gene, "
+ "class,"
+ "snp_id) "
+ "VALUES (DEFAULT, ?, ?, ?, ?, (SELECT id FROM snp s WHERE rsid = s.rsid))");
st.setString(1, fl.rsid);
st.setString(2, fl.mrna_acc);
st.setString(3, fl.gene);
st.setString(4, fl.classe);
st.executeUpdate();
st.close();
</code></pre>
<p>But when I fill in I have the following error:</p>
<blockquote>
<p>ERROR: more than one row returned by a subquery used as an expression</p>
</blockquote>
<p>Can you help me?
Thank you very much.</p>
| 3 | 1,940 |
Multiple Directive Resource Contention Error in Angular
|
<p>I have such definition of my custom directive: </p>
<pre><code>crmModule.directive("some", [function() {
return {
restrict: "E",
replace: true,
scope: {
itemModel: "=model"
},
templateUrl: "/Static/CRMpages/user-details-templates/preview-template.html",
link: function (scope, element, attrs) {
if (scope.itemModel.dueDateEnabled) {
scope.itemModel.date = scope.itemModel.dueDate.getDate();
scope.itemModel.month = scope.itemModel.dueDate.toLocaleDateString("en", { month: "short" }).toUpperCase();
scope.itemModel.time = scope.itemModel.dueDate.toLocaleTimeString("en", { hour: "numeric", minute: "numeric" });
}
scope.$watch('itemModel.dueDate', function() {
scope.itemModel.date = scope.itemModel.dueDate.getDate();
scope.itemModel.month = scope.itemModel.dueDate.toLocaleDateString("en", { month: "short" }).toUpperCase();
scope.itemModel.time = scope.itemModel.dueDate.toLocaleTimeString("en", { hour: "numeric", minute: "numeric" });
});
}
}}])
</code></pre>
<p>And in my HTML page I use it in following way: </p>
<pre><code><some model="actionModel"/>
</code></pre>
<p>In the same time I have main page, where I have button, when I click on this button I change route (I use <code>ui-router</code>) to <code>clients.action.edit</code> and load template <code>edit.html</code>:</p>
<pre><code><div class="action-plan-edit">
<div class="checkboxes col-sm-4">
<div class="due-date-section">
<div class="labels">
<input id="dueDateEnabled" type="checkbox" ng-model="actionModel.dueDateEnabled">
<span>Set due date</span>
</div>
<div class="dueDate-selector" slide open="actionModel.dueDateEnabled">
<div date-picker="actionModel.dueDate" nd-model="actionModel.dueDate" view="month" min-view="hours" max-view="month"></div>
<div class="selected-time">
<span class="date">{{actionModel.dueDate|itemDate}}</span>
<span class="time">{{actionModel.dueDate|itemTime}}</span>
</div>
</div>
</div>
<div class="booking-section">
<div class="labels">
<input id="bookingAttached" type="checkbox" ng-model="actionModel.bookingEnabled">
<span>Attach booking</span>
</div>
<div class="booking-attachment-area" slide open="bookingEnabled">
<select></select>
<select></select>
</div>
</div>
<div class="sms-section">
<div class="labels">
<input id="smsEnabled" type="checkbox" ng-model="actionModel.smsEnabled" >
<span>Send sms to client</span>
</div>
</div>
</div>
<div class="result-preview col-sm-6">
<div class="input-section">
<textarea class="crm-text-area" ng-model="actionModel.description" placeholder="Action description.."></textarea>
</div>
<div class="bordered-block">
<p class="preview-header">Live preview of action item</p>
<some model="actionModel"/>
</div>
<div class="save-button-section">
<button class="save-button" ng-click="saveItem()" ng-disabled="!itemValid">Save</button>
</div>
</div>
</div>
</code></pre>
<p>As you see a I use directive <code>some</code> in this page. Al needed files included, but I always got such error.</p>
<blockquote>
<p>Multiple directives [some, some] asking for template on: </p>
</blockquote>
<p>Help me please to resolve such issue.</p>
<p><strong>UPDATE</strong>: I found that link function of the directive called twice. Can it be an issue with <code>ui-router</code>?</p>
| 3 | 1,806 |
HelpNDoc online help not showing correct buttons and correct contents functionality
|
<p>When I visit this URL using Firefox on my PC:</p>
<p><a href="http://help-msa.publictalksoftware.co.uk/msa-options-calendars.html" rel="nofollow noreferrer">http://help-msa.publictalksoftware.co.uk/msa-options-calendars.html</a></p>
<p><a href="https://i.stack.imgur.com/ipJCD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ipJCD.jpg" alt="Firefox"></a></p>
<p>Yet, I have exactly the same site temporarily here:</p>
<p><a href="http://help.trucklesoft.co.uk/msa-options-calendars.html" rel="nofollow noreferrer">http://help.trucklesoft.co.uk/msa-options-calendars.html</a></p>
<p><a href="https://i.stack.imgur.com/pySLA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pySLA.jpg" alt="Firefox"></a></p>
<p>It renders correctly. The buttons have the right symbols and the contents is fully working.</p>
<p>The former link appears to show the buttons correct on a iPad with Safari but the contents is not functional.</p>
<p>My code is exactly the same on both sites. Why is it not working on the former?</p>
<p>The code is developed my HelpNDoc.</p>
<h1>Chrome Console</h1>
<p>When I look at the page with Chrome in the console it states:</p>
<blockquote>
<p>Access to Font at
<code>'https://help-msa.publictalksoftware.co.uk/vendors/bootstrap-3.3.6/fonts/glyphicons-halflings-regular.woff2'</code>
from origin <code>'http://help-msa.publictalksoftware.co.uk'</code> has been
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin
<code>'http://help-msa.publictalksoftware.co.uk'</code> is therefore not allowed
access.</p>
</blockquote>
<p>Huh? Is this related?</p>
<h1>Firefox Console</h1>
<blockquote>
<p>Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
<a href="https://help-msa.publictalksoftware.co.uk/vendors/bootstrap-3.3.6/fonts/glyphicons-halflings-regular.ttf" rel="nofollow noreferrer">https://help-msa.publictalksoftware.co.uk/vendors/bootstrap-3.3.6/fonts/glyphicons-halflings-regular.ttf</a>.
(Reason: CORS header 'Access-Control-Allow-Origin' missing).</p>
</blockquote>
<hr>
<h1>Update</h1>
<p>I think I worked it out. My <code>www.publictalks.co.uk</code> site is using the <strong>https</strong> protocol. If you go to the site using <code>http</code> You get redirected.</p>
<p>If I adjust the above link to:</p>
<p><a href="https://help-msa.publictalksoftware.co.uk/msa-options-calendars.html" rel="nofollow noreferrer">https://help-msa.publictalksoftware.co.uk/msa-options-calendars.html</a></p>
<p>It is fine:</p>
<p><a href="https://i.stack.imgur.com/RyKdi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RyKdi.jpg" alt="using https"></a></p>
<p>For some reason this subdomain <strong><code>help-msa</code></strong> is not redirecting to <strong><code>https</code></strong> site. </p>
<p>I did the above tests on my iPad and iPhone. I now need to check my PC.</p>
| 3 | 1,107 |
Confused with logic of login flow in AWS Developer Authenticated Identities
|
<p>I believe that I have an incorrect flow for implementing Developer Authenticated Identities and I keep hearing and doing different things on the web. So I thought I'd present my entire flow and hear what the correct way of doing this was and present some questions and errors at the bottom. </p>
<p>Initially, I have a user login with a password and username (I'm using nsuserdefaults only temporarily, I will use KeyChain later). </p>
<p>Note: I also have a callback that goes all the way down to see if I properly authenticated a user. </p>
<p>Login Method: </p>
<pre><code>-(void)loginBusyTimeUser:(void(^)(BOOL))callBack{
//initialize nsuserdefualts should be keychain later
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *post = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
[defaults objectForKey:@"username"], @"username",
[defaults objectForKey:@"password"], @"password",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:post options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"SOMELOGINURL"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *newJSON = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
if(!newJSON || [newJSON objectForKey:@"errorMessage"]){
NSLog(@"%@",newJSON);
callBack(false);
NSLog(@"DID NOT AUTHENTICATE");
}else{
NSLog(@"%@",newJSON);
[defaults setValue:[newJSON objectForKey:@"Token"] forKey:@"Token"];
[defaults setValue:[newJSON objectForKey:@"IdentityId"] forKey:@"IdentityId"];
[self authenticateUser:^(BOOL call){
callBack(call);
}];
}
}] resume];
</code></pre>
<p>}</p>
<p>If Everything is successful, I then authenticate my user with AWS Cognito with the developer authenticated flow: </p>
<pre><code>-(void)authenticateUser:(void(^)(BOOL))callBack{
//Now after making sure that your user's credentials are sound, then initialize the IdentityProvider, in this case
//BusytimeAuthenticated
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
id<AWSCognitoIdentityProvider> identityProvider = [[BusytimeAuthenticated alloc] initWithRegionType:AWSRegionUSEast1
identityId:nil
identityPoolId:@"SOMEPOOLID"
logins:@{@"cognito-identity.amazonaws.com": [defaults objectForKey:@"Token"]}
providerName:@"cognito-identity.amazonaws.com"
];
credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1
identityProvider:identityProvider
unauthRoleArn:nil
authRoleArn:nil];
configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1
credentialsProvider:self.credentialsProvider];
AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
[[credentialsProvider refresh] continueWithBlock:^id(AWSTask *task){
if([task isFaulted]){
callBack(false);
}else{
callBack(true);
}
return [defaults objectForKey:@"Token"];
}];
</code></pre>
<p>}</p>
<p>Then the refresh method causes some errors so I'll show my "BusytimeAuthenticated" class (.m) </p>
<pre><code>//
// BusytimeAuthenticated.m
// BusyTime
//
// Created by akash kakumani on 10/14/15.
// Copyright (c) 2015 BusyTime. All rights reserved.
//
#import "BusytimeAuthenticated.h"
@interface BusytimeAuthenticated()
@property (strong, atomic) NSString *providerName;
@property (strong, atomic) NSString *token;
@end
@implementation BusytimeAuthenticated
@synthesize providerName=_providerName;
@synthesize token=_token;
- (instancetype)initWithRegionType:(AWSRegionType)regionType
identityId:(NSString *)identityId
identityPoolId:(NSString *)identityPoolId
logins:(NSDictionary *)logins
providerName:(NSString *)providerName{
if (self = [super initWithRegionType:regionType identityId:identityId accountId:nil identityPoolId:identityPoolId logins:logins]) {
self.providerName = providerName;
}
return self;
}
// Return the developer provider name which you choose while setting up the
// identity pool in the Amazon Cognito Console
- (BOOL)authenticatedWithProvider {
return [self.logins objectForKey:self.providerName] != nil;
}
// If the app has a valid identityId return it, otherwise get a valid
// identityId from your backend.
- (AWSTask *)getIdentityId {
// already cached the identity id, return it
if (self.identityId) {
return [AWSTask taskWithResult:nil];
}
// not authenticated with our developer provider
else if (![self authenticatedWithProvider]) {
return [super getIdentityId];
}
// authenticated with our developer provider, use refresh logic to get id/token pair
else {
return [[AWSTask taskWithResult:nil] continueWithBlock:^id(AWSTask *task) {
if (!self.identityId) {
return [self refresh];
}
return [AWSTask taskWithResult:self.identityId];
}];
}
}
// Use the refresh method to communicate with your backend to get an
// identityId and token.
- (AWSTask *)refresh {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![self authenticatedWithProvider]) {
return [super getIdentityId];
}else{
NSDictionary *post = [[NSDictionary alloc] initWithObjectsAndKeys:
[defaults objectForKey:@"username"], @"username",
[defaults objectForKey:@"password"], @"password",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:post options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"SOMELOGINURL"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *newJSON = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
if(!newJSON){
NSLog(@"Failure in refresh: %@",newJSON);
}else{
NSLog(@"The IdentityID in the refresh method: %@",[newJSON objectForKey:@"IdentityId" ]);
NSLog(@"The token in the refresh method: %@",[newJSON objectForKey:@"Token" ]);
self.identityId = [newJSON objectForKey:@"IdentityId" ];
self.token = [newJSON objectForKey:@"Token" ];
}
}] resume];
return [AWSTask taskWithResult:self.identityId];
}
return [AWSTask taskWithResult:self.identityId];
}
@end
</code></pre>
<p>Some Questions I had: </p>
<ol>
<li><p>Is the DeveloperAuthenticationClient necessary to solve my problems? I saw the sample app using them but I found them too confusing. </p></li>
<li><p>Should I be using my ProviderName or should I be using "cognito-identity.amazonaws.com" </p></li>
<li><p>I sometimes face a timeout error and found out that it could be the fact that my implementation of login (using API Gateway and a lambda method) could have some cold-start issues. The way I solved this is by increasing the timeout time to 20 seconds. Is this the correct way to solve this? </p></li>
<li><p>I saw that in the sample app they use GetToken and Login as two separate things. I thought it would be easier if my login could also serve as my GetToken. Is this appropriate? </p></li>
<li><p>Finally, please address any problems that you see with my code if time permits. </p></li>
</ol>
<p>Error: </p>
<blockquote>
<p>[Error] AWSCredentialsProvider.m line:527 |
__40-[AWSCognitoCredentialsProvider refresh]_block_invoke352 | Unable to refresh. Error is [Error
Domain=com.amazonaws.AWSCognitoCredentialsProviderErrorDomain Code=1
"identityId shouldn't be nil"
UserInfo={NSLocalizedDescription=identityId shouldn't be nil}]</p>
</blockquote>
<p>(I also found out the error above is related to the fact that self.identityId didn't get set because the request was in a block and other parts executed first and the solution is: </p>
<pre><code>- (AWSTask *)refresh {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![self authenticatedWithProvider]) {
return [super getIdentityId];
}else{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *string = [defaults objectForKey:@"IdentityId"];
self.identityId = string;
return [AWSTask taskWithResult:[defaults objectForKey:@"IdentityId"]];
}
NSString *string = [defaults objectForKey:@"IdentityId"];
return [AWSTask taskWithResult:[defaults objectForKey:@"IdentityId"]];
}
</code></pre>
<p>But I believe that this isn't the correct implementation. )</p>
<p>I believe my code was working at a certain point but stopped working after I upgraded to the new SDK. However, it might just be the fact that I hadn't noticed the error initially. </p>
| 3 | 4,411 |
how to oauth twitter with Twitter4J api
|
<p>I want to authenticate twitter with Twitter4j api but it gives following error:</p>
<pre><code> 09-13 12:12:09.223: WARN/System.err(677): oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.
09-13 12:12:09.233: WARN/System.err(677): at oauth.signpost.basic.DefaultOAuthProvider.retrieveToken(DefaultOAuthProvider.java:74)
09-13 12:12:09.233: WARN/System.err(677): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:66)
09-13 12:12:09.233: WARN/System.err(677): at com.facebook.android.OAuthTwitter.onCreate(OAuthTwitter.java:45)
09-13 12:12:09.233: WARN/System.err(677): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
09-13 12:12:09.233: WARN/System.err(677): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
09-13 12:12:09.233: WARN/System.err(677): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
09-13 12:12:09.233: WARN/System.err(677): at android.app.ActivityThread.access$2100(ActivityThread.java:116)
09-13 12:12:09.243: WARN/System.err(677): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
09-13 12:12:09.243: WARN/System.err(677): at android.os.Handler.dispatchMessage(Handler.java:99)
09-13 12:12:09.243: WARN/System.err(677): at android.os.Looper.loop(Looper.java:123)
09-13 12:12:09.243: WARN/System.err(677): at android.app.ActivityThread.main(ActivityThread.java:4203)
09-13 12:12:09.243: WARN/System.err(677): at java.lang.reflect.Method.invokeNative(Native Method)
09-13 12:12:09.243: WARN/System.err(677): at java.lang.reflect.Method.invoke(Method.java:521)
09-13 12:12:09.243: WARN/System.err(677): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
09-13 12:12:09.243: WARN/System.err(677): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
09-13 12:12:09.243: WARN/System.err(677): at dalvik.system.NativeStart.main(Native method)
</code></pre>
<p>and i use the below code;</p>
<pre><code>public class OAuthTwitter extends Activity {
public final static String CALLBACK_URL = "callback://twitter"; // ----
// (4)
private CommonsHttpOAuthConsumer commonHttpOAuthConsumer;
private OAuthProvider authProvider;
private Twitter twitter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonHttpOAuthConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET); // ----- (5)
authProvider = new DefaultOAuthProvider(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"https://api.twitter.com/oauth/authorize");
try {
String oAuthURL = authProvider.retrieveRequestToken(
commonHttpOAuthConsumer, CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(oAuthURL)));
} catch (OAuthMessageSignerException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (OAuthCommunicationException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
protected void onNewIntent(Intent intent) { // ---- (6)
super.onNewIntent(intent);
Uri uri = intent.getData(); // ---- (7)
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
String verifier = uri
.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
try {
authProvider.retrieveAccessToken(commonHttpOAuthConsumer,
verifier); // ---- (8)
AccessToken accessToken = new AccessToken(
commonHttpOAuthConsumer.getToken(),
commonHttpOAuthConsumer.getTokenSecret()); // ---- (9)
twitter = new TwitterFactory().getInstance(); // ---- (10)
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(accessToken); // ---- (11)
// Tweet message to be updated.
String tweet = "Hiee there, This is send from my application - OAuth, Twitter";
twitter.updateStatus(tweet); // ---- (12)
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_LONG);
}
}
}
}
</code></pre>
<p>using the jars: signpost-commonshttp4-1.2.1.1.jar,signpost-core-1.2.jar,twitter4j-core-android-2.2.4.jar
plz anyone tell me where i am wrong.</p>
| 3 | 2,134 |
Problem to generate nested ul lists using PHP
|
<p>I am working on a front-end web app where a nested unordered list would be used for the jQuery plugin mcdropdown.</p>
<p>Here is the data structure from PHP: a nested array of arrays :</p>
<pre><code>Array
(
[0] => Array
(
[fullpath] => ../foil/alphanumeric/
[depth] => 0
)
[1] => Array
(
[fullpath] => ../foil/alphanumeric/letters/
[depth] => 1
)
[2] => Array
(
[fullpath] => ../foil/alphanumeric/numbers/
[depth] => 1
)
[3] => Array
(
[fullpath] => ../foil/alphanumeric/numbers/symbols/
[depth] => 2
)
)
</code></pre>
<p>Basically, I took the excellent answer from <a href="https://stackoverflow.com/questions/1310649/getting-a-modified-preorder-tree-traversal-model-nested-set-into-a-ul">this question on SO</a>, modified it a bit :</p>
<pre><code>global $fullpaths; // $fullpaths contains the above data structure in print_r
$result = '';
$currentDepth = -1;
while(!empty($fullpaths))
{
$currentNode = array_shift($fullpaths);
if($currentNode['depth'] > $currentDepth)
{
$result .='<ul>';
}
if($currentNode['depth'] < $currentDepth)
{
$result .=str_repeat('</ul>', $currentDepth - $currentNode['depth']);
}
$result .= '<li>'. $currentNode['fullpath'] .'</li>';
$currentDepth = $currentNode['depth'];
if(empty($fullpaths))
{
$result .= str_repeat('</ul>', 1 + $currentDepth);
}
}
print $result;
</code></pre>
<p>and got the following output:</p>
<pre><code><ul>
<li>../foil/alphanumeric/</li>
<ul>
<li>../foil/alphanumeric/letters/</li>
<li>../foil/alphanumeric/numbers/</li>
<ul>
<li>../foil/alphanumeric/numbers/symbols/</li>
</ul>
</ul>
</ul>
</code></pre>
<p>Which cannot be accepted by the mcdropdown jQuery plugin, it expects something like this:</p>
<pre><code><li rel="1">
'Alphanumeric'
<ul>
<li rel="2">'Letters'</li>
<li rel="3">'Numbers'
<ul>
<li rel="4">'Symbols'</li>
</ul>
</li>
</ul>
</li>
</code></pre>
<p>To be frank, I don't quite understand how the answer from that question works, I have been trying to modify that solution to cope with my situation, but still failed.</p>
<p>Any help and suggestion is much appropriated in advance.</p>
| 3 | 1,312 |
React all comment options appear by one click
|
<p>i have this code where I'm looping <code>post</code> array to extract <code>comments</code></p>
<pre><code>
const [commentOptions, setCommentOptions] = useState(false);
return(
...
{post.comments.map((comment) => (
<div className="comments" key={comment._id}>
<div className="commentUserImageAndUsername">
<img
className="commentUserImg"
src={
comment.userId === users._id
? users.profileImg || `${PF}/profile.jpg`
: null
}
alt="comment user "
/>
{comment.userId === users._id ? users.firstname : null}
</div>
<div className="commentBody">{comment.body}</div>
{user._id === comment.userId ? (
<div
className="commentOptionsMark"
onClick={() => setCommentOptions(!commentOptions)}
> - </div>
) : null}
{commentOptions ? (
<div className="commentOptions">
<div className="deleteComment">Delete</div>
<div className="editComment">Edit</div>
</div>
) : null}
</div>
))}
...
)
</code></pre>
<p>for every <code>comment</code> i have the <code>hyphen</code> mark <code>-</code>, if i click it, it will set the <code>commentOptions</code> state to true, therefore the <code>commentOptions div</code> will appear, which contains 2 options <code>delete comment</code> and <code>edit comment</code>, the problem with this is that if i click the <code>hyphen mark</code> for one comment, the <code>commentOptions div</code> will appear for every comment, like if there are 5 comments and every comment has its own options, i can control the appearance of <code>commentOptions div</code> for every comment by just one click, this is not what i want, i want to show one div for every comment <code>hyphen -</code> on click, not all of them at once, like every comment on its own, how to fix that?</p>
| 3 | 1,049 |
Django: store variables in database and pass them between different modules
|
<p>In my model I'm trying to calculate my user age and create for them an id code and I want this information to be saved in my database, but "age" and "id_code" fields are missing in my database. If I change the name of the function age and id variable are not computed at all.</p>
<pre><code>**accounts.models**
class UserInformation(models.Model):
name = models.CharField(max_length=250)
lastname = models.CharField(max_length=250)
phone = models.CharField(max_length=250)
birthday = models.DateField()
age = models.CharField(max_length=2)
id = models.CharField(max_length=250)
def __str__(self):
self.name + '_' + self.lastname + '_' + str(self.birthday.year)
def age(self):
age = datetime.now().year - int(self.birthdate.year)
return age
def id_code(self):
id_code = self.name + '_' + self.lastname + '_' + int(self.birthday.year)
return id_code
</code></pre>
<pre><code>**accounts.forms.py**
class UserInformationForm(forms.ModelForm):
class Meta:
model = UserInformation
fields = ('name', 'lastname', 'birthday', 'phone')
</code></pre>
<pre><code>**accounts.views.py**
def add_information(request):
if request.method == 'POST':
form = UserInformationForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('home')
else:
form = UserInformationForm()
return render(request, 'add_information.html', {'form': form})
</code></pre>
<p>I've also an another models file in another app where I've two quiz for my user. I'd like to save in my database with answers also the id code created in the other models file and use the userinformation answer to create the string name to use in the database but it gives me error <code>"'ImportError: cannot import name 'name' from 'accounts.models' " </code> even if I've imported the modules:</p>
<pre><code>**question.models.py**
from accounts.models import name
class QuestionOne(models.Model):
question_1a = models.CharField(max_length=250, choices=point)
question_2a = models.CharField(max_length=250, choices=point)
question_3a = models.CharField(max_length=250, choices=point)
id_code = models.CharField(max_length=250)
def __str__(self):
return self.name + '_question_1'
class QuestionTwo(models.Model):
question_1b = models.CharField(max_length=250, choices=point)
question_2b = models.CharField(max_length=250, choices=point)
question_3b = models.CharField(max_length=250, choices=point)
id_code = models.CharField(max_length=250)
def __str__(self):
return self.name + '_question_2'
</code></pre>
<pre><code>**question.forms.py**
class QuestionOneForm(forms.ModelForm):
class Meta:
model = QuestionOne
fields = ('question_1a', 'question_2a', 'question_3a')
class QuestionTwoForm(forms.ModelForm):
class Meta:
model = QuestionOne
fields = ('question_1b', 'question_2b', 'question_3b')
</code></pre>
<p>Lasltly in my html I'd like to show how many question forms have been completed so I added the "quest__done" variable. Unfortunly is not working and in my page <code>{{ quest_done }} </code>is just a blank space</p>
<pre><code>**question.views.py**
def question_one(request):
quest_done = 0
if request.method == 'POST':
form = QuestionOneForm(request.POST, request.FILES)
if form.is_valid():
quest_done += 1
form.instance.user = request.user
form.save()
return redirect('home')
else:
form = QuestionOneForm()
return render(request, 'quest.html', {'form': form, 'quest_done': quest_done})
def question_two(request):
quest_done = 0
if request.method == 'POST':
form = QuestionTwoForm(request.POST, request.FILES)
if form.is_valid():
quest_done += 1
form.instance.user = request.user
form.save()
return redirect('home')
else:
form = QuestionTwoForm()
return render(request, 'quest.html', {'form': form, 'quest_done': quest_done})
</code></pre>
<pre><code>*html**
<div class="row">
<div class="col-sm-3">
<h6 class="mb-0">Question form completed:</h6>
</div>
<div class="col-sm-9 text-secondary">
{{ quest_done }} /2
</div>
</div>
</code></pre>
| 3 | 1,890 |
Issue with include option in clang++
|
<p>I'm trying to compile a program with an "API" of my own. Let's say that my project's structure is:</p>
<pre><code>main.cc
...
api/
include/
*.h
lib/
libsdl2ecs.a
</code></pre>
<p>I know that compilers (or at least gcc and clang) have options to add directories to the include and lib paths (-I and -L), so the command I'm using to compile is:</p>
<pre><code>clang++ -std=c++11 -Iapi/include -Lapi/lib -Wall -o main main.cc -lSDL2 -lSDL2_image -lsdl2ecs
</code></pre>
<p>And it does not work: The output is too horrific to put it in here. Thing is, is not my problem, because if I remove the -Iapi/include option and write the whole paths in the .cc files it works flawlessly.</p>
<p>I would like to know if I am missing something.</p>
<p>Thanks in advance!</p>
<p>Edit: Error message</p>
<pre><code>clang++ -std=c++11 -Iapi/include/ -Lapi/lib/ -Wall -o main main.cc -lSDL2 -lSDL2_image -lsdl2ecs
In file included from main.cc:1:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/iostream:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ostream:38:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ios:42:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/bits/ios_base.h:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ext/atomicity.h:35:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr.h:148:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr-default.h:35:
In file included from /usr/include/pthread.h:23:
In file included from /usr/include/sched.h:34:
In file included from api/include/time.h:5:
api/include/system.h:15:9: error: implicit instantiation of undefined template 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >'
string failureDetail;
^
/usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/bits/stringfwd.h:71:11: note: template is declared here
class basic_string;
^
In file included from main.cc:1:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/iostream:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ostream:38:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ios:42:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/bits/ios_base.h:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ext/atomicity.h:35:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr.h:148:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr-default.h:35:
In file included from /usr/include/pthread.h:23:
In file included from /usr/include/sched.h:34:
In file included from api/include/time.h:6:
In file included from api/include/game.h:6:
In file included from api/include/entity.h:4:
api/include/component.h:24:9: error: implicit instantiation of undefined template 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >'
string failureDetail;
^
/usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/bits/stringfwd.h:71:11: note: template is declared here
class basic_string;
^
In file included from main.cc:1:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/iostream:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ostream:38:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ios:42:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/bits/ios_base.h:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ext/atomicity.h:35:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr.h:148:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr-default.h:35:
In file included from /usr/include/pthread.h:23:
In file included from /usr/include/sched.h:34:
In file included from api/include/time.h:6:
In file included from api/include/game.h:6:
In file included from api/include/entity.h:4:
api/include/component.h:70:6: error: member access into incomplete type 'Game'
game->Instantiate<T>();
^
api/include/system.h:4:7: note: forward declaration of 'Game'
class Game;
^
In file included from main.cc:1:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/iostream:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ostream:38:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ios:42:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/bits/ios_base.h:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ext/atomicity.h:35:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr.h:148:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr-default.h:35:
In file included from /usr/include/pthread.h:23:
In file included from /usr/include/sched.h:34:
In file included from api/include/time.h:6:
In file included from api/include/game.h:6:
In file included from api/include/entity.h:4:
api/include/component.h:77:15: error: member access into incomplete type 'Entity'
return entity->AddComponent<T>();
^
api/include/component.h:13:7: note: forward declaration of 'Entity'
class Entity;
^
api/include/component.h:84:15: error: member access into incomplete type 'Entity'
return entity->GetComponent<Derived>();
^
api/include/component.h:13:7: note: forward declaration of 'Entity'
class Entity;
^
In file included from main.cc:1:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/iostream:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ostream:38:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ios:42:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/bits/ios_base.h:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ext/atomicity.h:35:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr.h:148:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr-default.h:35:
In file included from /usr/include/pthread.h:23:
In file included from /usr/include/sched.h:34:
In file included from api/include/time.h:6:
In file included from api/include/game.h:6:
In file included from api/include/entity.h:6:
In file included from api/include/texture.h:8:
In file included from api/include/renderer.h:6:
api/include/display.h:14:9: error: implicit instantiation of undefined template 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >'
string title;
^
/usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/bits/stringfwd.h:71:11: note: template is declared here
class basic_string;
^
In file included from main.cc:1:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/iostream:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ostream:38:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ios:42:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/bits/ios_base.h:39:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/ext/atomicity.h:35:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr.h:148:
In file included from /usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/x86_64-redhat-linux/bits/gthr-default.h:35:
In file included from /usr/include/pthread.h:23:
In file included from /usr/include/sched.h:34:
In file included from api/include/time.h:6:
In file included from api/include/game.h:6:
In file included from api/include/entity.h:6:
api/include/texture.h:18:9: error: implicit instantiation of undefined template 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >'
string path;
^
/usr/bin/../lib/gcc/x86_64-redhat-linux/5.1.1/../../../../include/c++/5.1.1/bits/stringfwd.h:71:11: note: template is declared here
class basic_string;
^
In file included from main.cc:4:
In file included from ./prefabs.hh:2:
./ccomponents.hh:20:36: error: cannot initialize object parameter of type 'Component' with an expression of type 'WASDController'
Transform &transform = GetTransform();
^~~~~~~~~~~~
./ccomponents.hh:22:17: error: cannot initialize object parameter of type 'Component' with an expression of type 'WASDController'
if (GetKeyPressed(SDLK_d))
^~~~~~~~~~~~~
./ccomponents.hh:25:17: error: cannot initialize object parameter of type 'Component' with an expression of type 'WASDController'
if (GetKeyPressed(SDLK_w))
^~~~~~~~~~~~~
./ccomponents.hh:28:17: error: cannot initialize object parameter of type 'Component' with an expression of type 'WASDController'
if (GetKeyPressed(SDLK_a))
^~~~~~~~~~~~~
./ccomponents.hh:31:17: error: cannot initialize object parameter of type 'Component' with an expression of type 'WASDController'
if (GetKeyPressed(SDLK_s))
^~~~~~~~~~~~~
./ccomponents.hh:34:17: error: cannot initialize object parameter of type 'Component' with an expression of type 'WASDController'
if (GetKeyDown(SDLK_v))
^~~~~~~~~~
./ccomponents.hh:44:36: error: cannot initialize object parameter of type 'Component' with an expression of type 'Zoomer'
Transform &transform = GetTransform();
^~~~~~~~~~~~
./ccomponents.hh:46:17: error: cannot initialize object parameter of type 'Component' with an expression of type 'Zoomer'
if (GetKeyPressed(SDLK_x)) {
^~~~~~~~~~~~~
./ccomponents.hh:51:17: error: cannot initialize object parameter of type 'Component' with an expression of type 'Zoomer'
if (GetKeyPressed(SDLK_z)) {
^~~~~~~~~~~~~
./ccomponents.hh:63:36: error: cannot initialize object parameter of type 'Component' with an expression of type 'Rotator'
Transform &transform = GetTransform();
^~~~~~~~~~~~
./ccomponents.hh:65:17: error: cannot initialize object parameter of type 'Component' with an expression of type 'Rotator'
if (GetKeyPressed(SDLK_e))
^~~~~~~~~~~~~
./ccomponents.hh:68:17: error: cannot initialize object parameter of type 'Component' with an expression of type 'Rotator'
if (GetKeyPressed(SDLK_q))
^~~~~~~~~~~~~
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
Makefile:11: recipe for target 'main' failed
make: *** [main] Error 1
</code></pre>
| 3 | 5,357 |
html template to pdf with images
|
<p>I am using django and trying to render invoice pdf, pdf is generating successfully but images are not in pdf.</p>
<p>Actually I want to add barcode image, so I dynamically generated a <code>.svg</code> file, but don't know how to put it into pdf.</p>
<p>Here is what I am doing ..</p>
<pre><code>from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
</code></pre>
<p>html - </p>
<pre><code> <body>
<div class="container-fluid">
<div class="row">
<div class="col-6">
<div class="row">
<div class="col-12">
<span>
{{ package_no_barcode }}
<br>
{{ package.package_no }}
....
</code></pre>
<p>view - </p>
<pre><code>class GenerateInvoicePdf(View):
def get(self, request, *args, **kwargs):
package = Package.objects.get(package_no=request.GET.get('package'))
address = package.purchase.order_product.delivery_location
CODE128 = barcode.get_barcode_class('code128')
package_no_barcode = CODE128(u'{pkg_no}'.format(pkg_no=package.package_no))
if request.user.display_username == seller.display_username:
data = {
'package':package,
'address':address,
'package_no_barcode':package_no_barcode,
}
pdf = render_to_pdf('pdf/invoice.html', data)
if pdf:
response = HttpResponse(pdf, content_type='application/pdf')
filename = "Invoice_%s.pdf" %(package)
content = "inline; filename='%s'" %(filename)
download = request.GET.get("download")
if download:
content = "attachment; filename='%s'" %(filename)
response['Content-Disposition'] = content
return response
return HttpResponse("Not found")
</code></pre>
<p>I also tried with cid - <code><img src="cid:{{ package_no_barcode }}" alt="{{ package.package_no }}"></code></p>
<p><strong>Example of svg generated</strong></p>
<pre><code>CODE128 = barcode.get_barcode_class('code128')
package_no_barcode = CODE128(u'PLAI73664PJHS')
package_no_barcode.save('PSKK')
</code></pre>
<p>generate svg - </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 xmlns="http://www.w3.org/2000/svg" height="23.000mm" version="1.1" width="40.000mm">
<!--Autogenerated with python-barcode 0.9.0-->
<g id="barcode_group">
<rect height="100%" style="fill:white" width="100%"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="2.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="2.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="3.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.400mm" x="3.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="3.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.800mm" x="3.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="4.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="5.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="5.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="6.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="6.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="6.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="6.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.600mm" x="7.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="7.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="8.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="8.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="8.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="9.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="9.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="9.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.600mm" x="9.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="10.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.600mm" x="10.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="11.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.600mm" x="11.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="12.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.600mm" x="12.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="13.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="13.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="13.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="13.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="13.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="14.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.800mm" x="14.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="15.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="15.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.800mm" x="15.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="16.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="17.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="17.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.400mm" x="17.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="17.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.400mm" x="18.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="18.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.800mm" x="18.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="19.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="19.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="20.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="20.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.800mm" x="20.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="21.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="21.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="22.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="22.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.400mm" x="22.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="23.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.400mm" x="23.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="23.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="24.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="24.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="25.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="25.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="25.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="26.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="26.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="26.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="26.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="27.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="27.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="27.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.600mm" x="28.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="28.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.600mm" x="29.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="29.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="30.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="30.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.600mm" x="30.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="31.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="31.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="31.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="32.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="32.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.600mm" x="32.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="33.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.400mm" x="33.740mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="34.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="34.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="34.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.400mm" x="35.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="35.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.600mm" x="35.940mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.600mm" x="36.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="37.140mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.200mm" x="37.340mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:white;" width="0.200mm" x="37.540mm" y="1.000mm"/>
<rect height="15.000mm" style="fill:black;" width="0.400mm" x="37.740mm" y="1.000mm"/>
<text style="fill:black;font-size:10pt;text-anchor:middle;" x="20.340mm" y="21.000mm">PLAI73664PJHS</text>
</g>
</svg></code></pre>
</div>
</div>
</p>
<p><strong>Update</strong> - using <code>.render</code>, - <code>'package_no_barcode':package_no_barcode.render</code>, i can get the svg code but not for html - </p>
<pre><code>b'<?xml version="1.0" encoding="UTF-8"?>\r\n<!DOCTYPE svg\r\n PUBLIC \'-//W3C//DTD SVG 1.1//EN\'\r\n
\'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\'>\r\n<svg height="23.000mm" version="1.1" width="38.000mm" xmlns="http://www.w3.org/2000/svg">\r\n
<!--Autogenerated with python-barcode 0.9.0-->\r\n <g id="barcode_group">\r\n <rect height="100%" style="fill:white" width="100%"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.400mm" x="2.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm"
x="2.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="3.140mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.400mm" x="3.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="3.740mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.800mm" x="3.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.400mm" x="4.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="5.140mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.600mm" x="5.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm"
x="5.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="6.140mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.200mm" x="6.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="6.940mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm" x="7.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.200mm" x="8.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="8.340mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.400mm" x="8.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm"
x="8.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="9.140mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.600mm" x="9.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="10.340mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="10.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.400mm" x="10.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="11.140mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.600mm" x="11.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm"
x="11.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="12.140mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.600mm" x="12.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.400mm" x="12.940mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="13.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.200mm" x="13.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm" x="13.740mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.400mm" x="14.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm"
x="14.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="14.940mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.200mm" x="15.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="15.740mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.400mm" x="16.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.200mm" x="16.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="16.940mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.400mm" x="17.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.400mm"
x="17.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.400mm" x="17.940mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.400mm" x="18.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="18.740mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.400mm" x="18.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.600mm" x="19.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="19.940mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.400mm" x="20.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm"
x="20.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="21.140mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.200mm" x="21.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="21.540mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm" x="21.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.600mm" x="22.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm" x="22.940mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.200mm" x="23.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm"
x="23.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.400mm" x="23.940mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.200mm" x="24.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="24.540mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm" x="24.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.600mm" x="25.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="25.940mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.400mm" x="26.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm"
x="26.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="26.740mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.400mm" x="26.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.600mm" x="27.340mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="27.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.400mm" x="28.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.400mm" x="28.540mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.600mm" x="28.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm"
x="29.540mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="29.740mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.400mm" x="29.940mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.400mm" x="30.340mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.400mm" x="30.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.400mm" x="31.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm" x="31.540mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.200mm" x="32.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm"
x="32.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.200mm" x="32.940mm" y="1.000mm"/>\r\n <rect height="15.000mm"
style="fill:white;" width="0.200mm" x="33.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.400mm" x="33.340mm"
y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.600mm" x="33.740mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;"
width="0.600mm" x="34.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm" x="34.940mm" y="1.000mm"/>\r\n <rect
height="15.000mm" style="fill:black;" width="0.200mm" x="35.140mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:white;" width="0.200mm"
x="35.340mm" y="1.000mm"/>\r\n <rect height="15.000mm" style="fill:black;" width="0.400mm" x="35.540mm" y="1.000mm"/>\r\n <text
style="fill:black;font-size:10pt;text-anchor:middle;" x="19.240mm" y="21.000mm">UXXWL94HXO08</text>\r\n </g>\r\n</svg>\r\n'
</code></pre>
<p>How to make svg image with this code ?</p>
| 3 | 11,025 |
R - Quantstrat Issue with prefer and getPrice
|
<p>Currently working on a strategy in quantstrat using Quandl futures data. However, when I try to applyStrategy() after adding indicators, signals and order rules, I receive the following error message, <code>Error in getPrice(mktdata, prefer = prefer) : object 'prefer' not found</code>. <code>applyIndicators()</code> and <code>applySignals()</code> works well when debugging so the error is most likely in the processing of the rules. Below is the tail end of the mktdata variable that results after applying the signals in addition to the end part of the code.</p>
<p>mktdata:</p>
<p><img src="https://i.stack.imgur.com/8WSO9.jpg" alt="enter image description here"></p>
<p>Code:</p>
<pre><code>initPortf(portfolio.mom, symbols=allInstruments, initDate=initDate, currency='USD')
initAcct(account.mom, portfolios=portfolio.mom, initDate=initDate, currency='USD')
initOrders(portfolio.mom, initDate=initDate)
strategy(strategy.mom, store=TRUE)
#Indicators
strategy.mom <- add.indicator(strategy=strategy.mom, name="tsMOM", arguments=list(futDataRet = quote(Cl(mktdata)), momLookback=momLookback, tradingDays=tradingDays), label="tsMOM")
strategy.mom <- add.indicator(strategy=strategy.mom, name="retVol", arguments=list(futDataRet = quote(Cl(mktdata)), volLookback=volLookback, tradingDays=tradingDays), label="retVol")
#Signals
strategy.mom <- add.signal(strategy.mom,name="sigThreshold",arguments=list(threshold=posTradeThresh, column="tsMOM", relationship="gt", cross=FALSE), label="LongCond")
strategy.mom <- add.signal(strategy.mom,name="sigThreshold",arguments=list(threshold=negTradeThresh, column="tsMOM", relationship="lt", cross=FALSE), label="ShortCond")
strategy.mom <- add.signal(strategy.mom, name="sigFormula", arguments=list(columns=c("tsMOM","LongCond"), formula="((LongCond != 1) & (tsMOM >= 0))", cross=FALSE), label="NeutralPosCond")
strategy.mom <- add.signal(strategy.mom, name="sigFormula", arguments=list(columns=c("tsMOM","ShortCond"), formula="((tsMOM < 0) & (ShortCond != 1))", cross=FALSE), label="NeutralNegCond")
# Entry Rule
strategy.mom <- add.rule(strategy.mom, name="ruleSignal", arguments=list(sigcol="LongCond", sigval=TRUE, orderqty=1000, ordertype="market", orderside="long", prefer = "Close", TxnFees = -100), type="enter")
strategy.mom <- add.rule(strategy.mom, name="ruleSignal", arguments=list(sigcol="ShortCond", sigval=TRUE, orderqty=1000, ordertype="market", orderside="short", prefer = "Close", TxnFees = -100), type="enter")
# Exit Rule
strategy.mom <- add.rule(strategy.mom, name="ruleSignal", arguments=list(sigcol="NeutralPosCond", sigval=TRUE, orderqty="all", ordertype="market", orderside="short", prefer = "Close", TxnFees = -100), type="exit")
strategy.mom <- add.rule(strategy.mom, name="ruleSignal", arguments=list(sigcol="NeutralNegCond", sigval=TRUE, orderqty="all", ordertype="market", orderside="long", prefer = "Close", TxnFees = -100), type="exit")
applyStrategy(strategy=strategy.mom, portfolios=portfolio.mom, prefer="Close")
updatePortf(portfolio.mom)
updateAcct(account.mom)
updateEndEq(account.mom)
</code></pre>
<p>Output of <code>sessionInfo()</code>:</p>
<p><img src="https://i.stack.imgur.com/jgiLO.jpg" alt="enter image description here"></p>
| 3 | 1,132 |
Making falling objects come at random angles in AS3
|
<p>I am making a missile defense type of game and am trying to get the missiles to fall at random angles. I also need the bullet image to turn at the angle I am shooting at. I am very unfamiliar with angles in AS3 so I need some help.</p>
<p>Code:
<pre><code> import spark.components.Image;
public var missiles:Array;
public var bullets:Array;
public var playerLife:Number;
public var targetX:Number;
public var targetY:Number;
public function init():void {
startGame();
}
public function onEnterFrame(e:Event):void {
if(Math.random() <.05 ){
//make a new missle
var newMissile:Image = new Image();
//draw to is
newMissile.source = "assets/missileDown.jpg";
//position it
newMissile.x = Math.random() * stage.stageWidth;
//animate it
newMissile.addEventListener(Event.ENTER_FRAME, onMissileEnterFrame);
//add it to missle array
missiles.push(newMissile);
//add it to the screen
gameGroup.addElement(newMissile);
}
}
public function startGame():void {
//makes new arrays
//gets rid of old arrays
missiles = new Array();
bullets = new Array();
//set player life
playerLife = 5;
//show player life
playerHealth.text = String(playerLife);
//add animation and mouse interation
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
stage.addEventListener(MouseEvent.CLICK, fireWeapon);
//set game over alpha
gameEnd.alpha = 0;
reset.alpha = 0;
//set game start alpha
playerHealth.alpha = 1;
healthLabel.alpha = 1;
}
//updates the missle
public function onMissileEnterFrame(e:Event):void {
//reference to target
var targetMissile:Image = Image(e.currentTarget);
//move missle down
targetMissile.y += 10;
//if missle has gone too far, remove it and player loses life
if(targetMissile.y > stage.stageHeight) {
playerLife --;
removeMissile(targetMissile);
//show player life
playerHealth.text = String(playerLife);
}
//if player is dead, game over
if(playerLife <= 0) {
gameOver();
}
}
//update bullet
public function onBulletEnterFrame(e:Event):void {
//get reference to bullet
var thisBullet:Bullet = Bullet(e.currentTarget);
//animate towards point..
//calculate difference between current position and desired position
var diffX:Number = thisBullet.targX - thisBullet.x;
var diffY:Number = thisBullet.targY - thisBullet.y;
//move 10% of difference closer
thisBullet.x += diffX * .1;
thisBullet.y += diffY * .1;
//chekc for overlap between bullet and missles
for(var i:Number = 0; i < missiles.length; i++) {
//if they do overlap, remove missle
if( thisBullet.hitTestObject(missiles[i]) ) {
removeMissile(missiles[i]);
removeBullet(thisBullet);
break;
}
}
//if we're 'close enough' to the target position, remove bullet
if(Math.abs(diffX) < 10 && Math.abs(diffY) < 10) {
removeBullet(thisBullet);
}
}
//gets rid of a missle
public function removeMissile(targetMissile:Image):void {
//removes the missle from the missiles array
for(var i:Number = missiles.length - 1; i >= 0; i--) {
if(missiles[i] == targetMissile) {
missiles.splice(i,1);
break;
}
}
//don't animate anymore
targetMissile.removeEventListener(Event.ENTER_FRAME, onMissileEnterFrame);
//remove from stage
gameGroup.removeElement(targetMissile);
}
//removes bullet from stage
public function removeBullet(targetBullet:Bullet):void {
//stop animation
targetBullet.removeEventListener(Event.ENTER_FRAME, onBulletEnterFrame);
//remove from stage
gameGroup.removeElement(targetBullet);
}
//shoot a bullet at the mouse position
public function fireWeapon(e:MouseEvent):void {
//make a new bullet
var newBullet:Bullet = new Bullet();
newBullet.addEventListener(Event.ENTER_FRAME, onBulletEnterFrame);
//position near the earth in the center
var halfStage:Number = stage.stageWidth / 2;
newBullet.x = halfStage;
newBullet.y = 500;
//set target
newBullet.targX = stage.mouseX;
newBullet.targY = stage.mouseY;
//add it to the stage
gameGroup.addElement(newBullet);
}
//you lose
public function gameOver():void {
//remove missles
for(var i:Number = 0; i < missiles.length; i++) {
removeMissile(missiles[i]);
}
//stop interaction
stage.removeEventListener(MouseEvent.CLICK, fireWeapon);
//stop animation
this.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
//set game start alpha
playerHealth.alpha = 0;
healthLabel.alpha = 0;
//set game end alpha
gameEnd.alpha = 1;
reset.alpha = 1;
}
]]>
</fx:Script>
</code></pre>
| 3 | 2,976 |
Can't seem to get GetRelativeRotation() to work in Unreal C++
|
<p>According to the unreal documentation, GetRelativeRotation is a member variable of USceneComponent. However, when I run my code, it tells me that it's not. I have tried switching my Camera to a UCameraComponent(as it was originally before I checked the documenation) and still no luck. Any ideas? heres the code for the .cpp file:</p>
<pre><code>#include "FirstPersonCharacter.h"
AFirstPersonCharacter::AFirstPersonCharacter()
{
PrimaryActorTick.bCanEverTick = true;
AutoPossessPlayer = EAutoReceiveInput::Player0;
bUseControllerRotationYaw = false;
Cam = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
Cam->AttachTo(RootComponent);
Cam->SetRelativeLocation(FVector(0.f, 0.f, 40.f)); //places the camera 40cm above the centre of the body.
}
void AFirstPersonCharacter::BeginPlay()
{
Super::BeginPlay();
}
void AFirstPersonCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AFirstPersonCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
InputComponent->BindAxis("HorizontalMovement", this, &AFirstPersonCharacter::HorizontalMove);
InputComponent->BindAxis("VerticalMovement", this, &AFirstPersonCharacter::VerticalMove);
InputComponent->BindAxis("VerticalLook", this, &AFirstPersonCharacter::VerticalRot);
InputComponent->BindAxis("HorizontalLook", this, &AFirstPersonCharacter::HorizontalRot);
}
void AFirstPersonCharacter::HorizontalMove(float value)
{
if (value) //make sure it doesn't constantly call on addmovementinput if theres no value to add to it
{
AddMovementInput(GetActorRightVector(), value);
}
}
void AFirstPersonCharacter::VerticalMove(float value)
{
if (value) //make sure it doesn't constantly call on addmovementinput if theres no value to add to it
{
AddMovementInput(GetActorForwardVector(), value);
}
}
void AFirstPersonCharacter::HorizontalRot(float value)
{
if (value)
{
AddActorLocalRotation(FRotator(0, value, 0));
}
}
void AFirstPersonCharacter::VerticalRot(float value)
{
if (value)
{
float temp = Cam->GetRelativeRotation().Pitch + value; //THIS IS WHERE THE ISSUE IS
if (temp < 65 && temp > -65)
{
Cam->AddLocalRotation(FRotator(value, 0, 0));
}
}
</code></pre>
<p>and the code for the header file:</p>
<pre><code>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "Components/InputComponent.h"
#include "Components/SceneComponent.h"
#include "Camera/CameraComponent.h"
#include "FirstPersonCharacter.generated.h"
UCLASS()
class MOMENTUMPROJECTMAIN_API AFirstPersonCharacter : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
AFirstPersonCharacter();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
private:
void HorizontalMove(float value);
void VerticalMove(float value);
void HorizontalRot(float value);
void VerticalRot(float value);
//allows me to edit in the editor, without going into source code.
UPROPERTY(EditAnywhere, Category = "Camera")
UCameraComponent* Cam;
};
</code></pre>
<p>thanks.</p>
| 3 | 1,346 |
How to access Camunda Cloud from inside corporate network
|
<p>I’m building a PoC with Zeebe</p>
<p>I was able to run from my local pc the Java client at <a href="https://github.com/camunda-cloud/camunda-cloud-get-started" rel="nofollow noreferrer">https://github.com/camunda-cloud/camunda-cloud-get-started</a></p>
<p>Now, when I try to run it from my corporate PC, I’m getting the error below. I understand that I need to fix some network configuration to make it work. Is this configuration documented anywhere?</p>
<p>Many thanks.</p>
<hr />
<pre><code>18:42:51.788 [grpc-default-executor-0] WARN io.camunda.zeebe.client.job.poller - Failed to activated jobs for worker default and job type email
io.grpc.StatusRuntimeException: DEADLINE_EXCEEDED: deadline exceeded after 19.913053500s. [closed=[], open=[[buffered_nanos=19915792700, waiting_for_connection]]]
at io.grpc.Status.asRuntimeException(Status.java:535) ~[grpc-api-1.40.1.jar:1.40.1]
at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:478) [grpc-stub-1.40.1.jar:1.40.1]
at io.grpc.internal.DelayedClientCall$DelayedListener$3.run(DelayedClientCall.java:463) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.DelayedClientCall$DelayedListener.delayOrExecute(DelayedClientCall.java:427) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.DelayedClientCall$DelayedListener.onClose(DelayedClientCall.java:460) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:557) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:69) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:738) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:717) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133) [grpc-core-1.40.1.jar:1.40.1]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?]
at java.lang.Thread.run(Thread.java:834) [?:?]
18:42:53.374 [grpc-default-executor-2] WARN io.camunda.zeebe.client.job.poller - Failed to activated jobs for worker default and job type email
io.grpc.StatusRuntimeException: UNAVAILABLE: io exception
at io.grpc.Status.asRuntimeException(Status.java:535) ~[grpc-api-1.40.1.jar:1.40.1]
at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onClose(ClientCalls.java:478) [grpc-stub-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:557) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:69) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:738) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:717) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37) [grpc-core-1.40.1.jar:1.40.1]
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:133) [grpc-core-1.40.1.jar:1.40.1]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?]
at java.lang.Thread.run(Thread.java:834) [?:?]
Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection timed out: no further information: d05e6b8a-51ef-45b1-a532-0fe11c01f0e4.bru-2.zeebe.camunda.io/34.76.215.247:443
Caused by: java.net.ConnectException: Connection timed out: no further information
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[?:?]
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:779) ~[?:?]
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:330) ~[netty-transport-4.1.68.Final.jar:4.1.68.Final]
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334) ~[netty-transport-4.1.68.Final.jar:4.1.68.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:707) ~[netty-transport-4.1.68.Final.jar:4.1.68.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655) ~[netty-transport-4.1.68.Final.jar:4.1.68.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581) ~[netty-transport-4.1.68.Final.jar:4.1.68.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493) ~[netty-transport-4.1.68.Final.jar:4.1.68.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986) ~[netty-common-4.1.68.Final.jar:4.1.68.Final]
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.68.Final.jar:4.1.68.Final]
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.68.Final.jar:4.1.68.Final]
... 1 more
</code></pre>
| 3 | 2,214 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.