id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23535900
|
Well, the problem is: I have to update 30K entities into database (EF 4.1, POCO). The entity type is quite simple containing integer Id + other 4 integer properties with no relations to other types. 2 cases:
*
*all them are new records. Running context.Entities.Add(entity) one by one for every entity takes 90 seconds with Cntx.Configuration.AutoDetectChangesEnabled=false (true value makes it run forever). Then SaveChanges takes just a second. Other approach: attaching it to the context like this takes the same 90 sec:
Cntx.Entities.Attach(entity);
Cntx.Entry(entity).State = EntityState.Added;
*all them are existing records with some changes. In the case it takes just few milliseconds to attach it to existing data context like this:
Cntx.Entities.Attach(entity);
Cntx.Entry(entity).State = EntityState.Modified;
See the difference?
What is behind the scene of Add method that makes it work so incredibly slow?
A: I've got interesting performance testing results and I've found a culprit. I have not seen any information like this in any EF source I've ever read.
It turns out to be Equals overridden in a base class. The base class supposed to contain Id property shared between all types of concrete entities. This approach recommended by many EF books and pretty well know. You can find it here for example: How to best implement Equals for custom types?
More exactly, performance is killed by unboxing operation (object to concrete type conversion) that made it work so slow. As I commented this line of code it took 3 sec to run opposing to 90 sec before!
public override bool Equals ( object obj )
{
// This line of code made the code so slow
var entityBase = obj as EntityBase;
...
}
As I found it I started thinking over what might be an alternative to this Equals. First idea was to implement IEquatable for EntityBase, but it happened not to be run at all. So what I decided finally to do is to implement IEquatable for each concrete entity class in my model. I have only few of them, so it's minor update for me. You can put whole Equal operation functionality (usually it is 2 object Ids comparison) into extension method to share between concrete entity classes and run it like this: Equal((EntityBase)ConcreteEntityClass). The most interesting, this IEquatable speeds up EntitySet.Add 6 times!
So I have no more issues with performance, the same code runs for me with less than a second. I got 180 times performance gain! Amazing!
Conclusion:
*
*the most fast way to run EntitySet.Add is to have IEquatable for the specific entity (0.5 sec)
*Missing IEquatable makes it run 3 sec.
*Having Equals(object obj) which most sources recommend makes it run 90 sec
| |
doc_23535901
|
Meaning, i have to compare those:
struct Identifier
{
string name;
string email;
}
with the two strings name and email.
I know i could just create a new Identifier instance for name and email and pass that into equals(). My application has to be very fast and resource-saving.
I know that comparison via hashcode isn't a good way, because as explained here there are collisions. But collisions are okay for me, i just need it to be fast.
So,
1) is comparison via GetHashCode (check if the hashcode of both objects are the same) faster than Equals()?
2) Should i instead creating a new instance of Identifier of the two values for the comparison, make a new method which takes the values directly? e.g.
struct Identifier {
string name;
string email;
bool Equals(string name, string email) {
// todo comparison via hashcode or equals
}
}
I would use the Equals() and GetHashCode() method generated by resharper.
A:
is comparison via GetHashCode (check if the hashcode of both objects
are the same) faster than Equals()?
You seem to be confusing the two concepts. GetHashCode's purpose isn't to seek equality between two object instances, it is there simply so each object can easily provide a hashcode value for any external resources that may relay on it.
Equals, on the other hand, is there to determine equality. It should be that two methods which yield true for equals, provide the same hashcode, but not the other way around.
The documentation on object.GetHashCode provides a pretty good explanation:
Two objects that are equal return hash codes that are equal. However,
the reverse is not true: equal hash codes do not imply object
equality, because different (unequal) objects can have identical hash
codes. Furthermore, the .NET Framework does not guarantee the default
implementation of the GetHashCode method, and the value this method
returns may differ between .NET Framework versions and platforms, such
as 32-bit and 64-bit platforms. For these reasons, do not use the
default implementation of this method as a unique object identifier
for hashing purposes. Two consequences follow from this:
*
*You should not assume that equal hash codes imply object equality.
*You should never persist or use a hash code outside the application domain in
which it was created, because the same object may hash across
application domains, processes, and platforms.
If you want to check for equality between two instances, I definitely recommend implementing IEquatable<T> and overriding object.GetHashCode.
As a side note - I see that you're using a struct. You should note that struct has different semantics in C# than in C++ or C, and I hope you're aware of them.
A: Comparing hash codes could be faster if you save them on the Identifier instance (see below). However, it is not the same thing as comparing for equality.
Comparing hash codes lets you check if two items are definitely not equal to each other: you know this when you get different hash codes.
When hash codes are equal, however, you cannot make a definitive statement about the equality: the items could be equal or not equal to each other. That is why hash-based containers must always follow hash code comparison, direct or indirect, with a comparison for equality.
Try implementing the comparison like this:
struct Identifier {
string name;
string email;
int nameHash;
int emailHash;
public Identifier(string name, string email) {
this.name = name;
nameHash = name.GetHashCode();
this.email = email;
emailHash = email.GetHashCode();
}
bool Equals(string name, string email) {
return name.GetHashCode() == nameHash
&& email.GetHashCode() == emailHash
&& name.equals(this.name)
&& email.equals(this.email);
}
}
Comparing to pre-computed hash code would short-circuit the actual equality comparison, so you could save some CPU cycles when most of the comparisons end up returning false.
| |
doc_23535902
|
This is the method
$.ajax({
method: "POST",
url: "<?php echo base_url()?>empleadoController/save_empleado",
type:"POST",
data: {
"fecha_ingreso": fecha_ingreso,
"direccion": direccion ,
"nombrecompleto": nombrecompleto,
"cedula": cedula ,
"carnet":carnet ,
"telefono": telefono ,
"observaciones": observaciones ,
"email": email,
"dominioempleado": dominioempleado ,
"usr_open": usr_open ,
"usr_oda": usr_oda ,
"usr_qflow": usr_qflow ,
"usr_webclient": usr_webclient ,
"usr_siv": usr_siv ,
"tienda": tienda ,
"empresa": empresa ,
"funcion": funcion
},
success: function (data) {
alert("Realizado");
},
error: function (data) {
alert("Error");
}
});
});
The data array obtain successfully the information, but in the controller i keep receiving this message
A Database Error Occurred
Error Number: 23502/7
ERROR: null value in column "idtienda" violates not-null constraint DETAIL: Failing row contains (716, null, null, null, SIN CEDULA, FIZUNCH, uploads/default-user.png, , , SIN TELEFONO, SIN DIRECCION, 01-01-1970, SIN OBSERVACIONES, t, SIN DOMINIO).
INSERT INTO "tbl_ctrl_empleados" ("idtienda", "idtipoempresa", "idfuncion", "cedula", "carnetempleado", "rutafoto", "nombrecompleto", "email", "telefono", "direccion", "fecha_ingreso", "observaciones", "estado", "dominioempleado") VALUES (NULL, NULL, NULL, 'SIN CEDULA', 'FIZUNCH', 'uploads/default-user.png', '', '', 'SIN TELEFONO', 'SIN DIRECCION', '01-01-1970', 'SIN OBSERVACIONES', TRUE, 'SIN DOMINIO')
Filename: C:/xampp/htdocs/MasterKey/system/database/DB_driver.php
Line Number: 691
But the information goes directly and save it
715;45;6;9;"0012208950011K";"010101";"uploads/default-user.png";"LUIS ALFONSO VELAZQUEZ FLOREZA";"LUID@HOTMAIL.COM";"22334411";"NO LO SE";"01-01-1970";"AQUI";TRUE;"AQUI"
Please advice me what im doing wrong.
update
The schema from my table it's
CREATE TABLE key.tbl_ctrl_empleados
(
idempleado serial NOT NULL,
idtienda integer NOT NULL,
idtipoempresa integer NOT NULL,
idfuncion integer NOT NULL,
cedula character varying(20) NOT NULL,
carnetempleado character varying(100) NOT NULL,
rutafoto character varying(300),
nombrecompleto character varying(300) NOT NULL,
email character varying(100) NOT NULL,
telefono character varying(50) NOT NULL,
direccion character varying(500) NOT NULL,
fecha_ingreso character varying(50) NOT NULL,
observaciones character varying(300) NOT NULL,
estado boolean NOT NULL DEFAULT true,
dominioempleado character varying(300) NOT NULL,
CONSTRAINT tbl_ctrl_empleados_pkey PRIMARY KEY (idempleado),
CONSTRAINT tbl_ctrl_empleados_idfuncion_fkey FOREIGN KEY (idfuncion)
REFERENCES key.cat_ctrl_funcion (idfuncion) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT tbl_ctrl_empleados_idtienda_fkey FOREIGN KEY (idtienda)
REFERENCES key.tbl_ctrl_tiendas (idtienda) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT tbl_ctrl_empleados_idtipoempresa_fkey FOREIGN KEY (idtipoempresa)
REFERENCES key.ft_ctrl_rel_tipoempresa (idrelacion) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE key.tbl_ctrl_empleados
OWNER TO postgres;
The method in my controller:
function save_empleado() {
$valoresReemplazoCedula = array(
'-' => '',
'N/A' => 'SIN CEDULA',
"''" => 'SIN CEDULA'
);
$valoresReemplazoCarnet = array(
'-' => '',
'N/A' => 'SIN CARNET',
"''" => 'SIN CARNET'
);
$valoresReemplazoEmail = array(
'-' => '',
'N/A' => 'SIN EMAIL',
"''" => 'SIN EMAIL'
);
$valoresReemplazoTelefono = array(
'-' => '',
' ' => '',
'N/A' => 'SIN TELEFONO',
"''" => 'SIN TELEFONO'
);
$valoresReemplazoDominio = array(
'-' => '',
'N/A' => 'SIN DOMINIO',
"''" => 'SIN DOMINIO'
);
$valoresReemplazoNombre = array(
'-' => '',
'N/A' => 'SIN NOMBRE',
"''" => 'SIN NOMBRE'
);
$valoresReemplazoObservacion = array(
'N/A' => 'SIN OBSERVACIONES',
"''" => 'SIN OBSERVACIONES'
);
$valoresReemplazoDireccion = array(
'N/A' => 'SIN DIRECCION',
"''" => 'SIN DIRECCION'
);
$valoresReemplazoOPEN = array(
'-' => '',
'N/A' => 'SIN OPEN',
"''" => 'SIN OPEN'
);
$valoresReemplazoODA = array(
'-' => '',
'N/A' => 'SIN ODA',
"''" => 'SIN ODA'
);
$valoresReemplazoWC = array(
'-' => '',
'N/A' => 'SIN WEBCLIENT',
"''" => 'SIN WEBCLIENT'
);
$valoresReemplazoSIV = array(
'-' => '',
'N/A' => 'SIN SIV',
"''" => 'SIN SIV'
);
$valoresReemplazoQFLOW = array(
'-' => '',
'N/A' => 'SIN QFLOW',
"''" => 'SIN QFLOW'
);
$this->load->model('EmpleadoModel');
// $fechaingresos = $fechaingreso->format('d/m/Y');
// $fechaingresos = $this->input->post("fecha_ingreso");
//$fechaingreso= DateTime::createFromFormat('Y-m-d',$this->input->post("date"));
//$fechaingreso= DateTime::createFromFormat('Y-m-d',$this->input->post("fecha_ingreso"))->format('d/m/Y');
//echo Datetime::createFromFormat('Y-m-d', $this->input->post("fecha_ingreso"))->format('d/m/Y');
$fechaingreso=$this->input->post("fecha_ingreso");
$time = strtotime($fechaingreso);
$fecha = date('d/m/Y',$time);
$direcciones=$this->reemplazarCadenaAsoc($valoresReemplazoDireccion, preg_replace('/\s+/', ' ',ltrim($this->input->post("direccion"))));
$nombre=$this->reemplazarCadenaAsoc($valoresReemplazoNombre, preg_replace('/\s+/', ' ',ltrim($this->input->post("nombrecompleto"))));
$cedula=$this->reemplazarCadenaAsoc($valoresReemplazoCedula, preg_replace('/\s+/', '',ltrim($this->input->post("cedula"))));
$carnet=$this->reemplazarCadenaAsoc($valoresReemplazoCarnet, preg_replace('/\s+/', '',ltrim($this->input->post("carnet"))));
$telefono=$this->reemplazarCadenaAsoc($valoresReemplazoTelefono, preg_replace('/\s+/', ' ',ltrim($this->input->post("telefono"))));
$observaciones=$this->reemplazarCadenaAsoc($valoresReemplazoObservacion, preg_replace('/\s+/', ' ',ltrim($this->input->post("observaciones"))));
$email=$this->reemplazarCadenaAsoc($valoresReemplazoEmail, preg_replace('/\s+/', ' ',ltrim($this->input->post("email"))));
$dominios=$this->reemplazarCadenaAsoc($valoresReemplazoDominio, preg_replace('/\s+/', '',ltrim($this->input->post("dominioempleado"))));
$usr_open=$this->reemplazarCadenaAsoc($valoresReemplazoOPEN, preg_replace('/\s+/', '',ltrim($this->input->post("usr_open"))));
$usr_oda=$this->reemplazarCadenaAsoc($valoresReemplazoODA, preg_replace('/\s+/', '',ltrim($this->input->post("usr_oda"))));
$usr_qflow=$this->reemplazarCadenaAsoc($valoresReemplazoQFLOW, preg_replace('/\s+/', '',ltrim($this->input->post("usr_qflow"))));
$usr_webclient=$this->reemplazarCadenaAsoc($valoresReemplazoWC, preg_replace('/\s+/', '',ltrim($this->input->post("usr_webclient"))));
$siv=$this->reemplazarCadenaAsoc($valoresReemplazoSIV, preg_replace('/\s+/', '',ltrim($this->input->post("usr_siv"))));
$flag=$this->EmpleadoModel->existe_empleado($carnet,$cedula);
if ($flag === true) {
echo '<script>alert("El numero de carnet ya se encuentra registrado.")</script>';
return;
}
$fechaingreso = DateTime::createFromFormat('Y-m-d', $this->input->post("fecha_ingreso"));
if (empty($carnet)) {
$carnet = $this->generarAleatorio(7);
}
if( empty($direcciones)){
$direcciones = 'Sin Direccion';
}
if( empty($observaciones)){
$observaciones = 'Sin Observaciones';
}
if( empty($telefono) || $telefono == '0'){
$telefono = 'Sin Telefono';
}
if( empty($dominios) || strcasecmp($dominios, 'No tiene') == 0){
$dominios = 'Sin Dominio';
}
if( empty($cedula)){
$cedula = 'Sin Cedula';
}
$save = array('idtienda'=>$this->input->post("tienda"),'idtipoempresa'=>$this->input->post("empresa"),'idfuncion'=>$this->input->post("funcion"),'cedula'=>strtoupper($cedula),'carnetempleado'=>strtoupper($carnet),
'rutafoto'=>("uploads/default-user.png"),'nombrecompleto'=>strtoupper($nombre),'email'=>strtoupper($email),'telefono'=>strtoupper($telefono),'direccion'=>strtoupper($direcciones),
'fecha_ingreso'=>$fecha,'observaciones'=>strtoupper($observaciones),'estado'=>(true),'dominioempleado'=>strtoupper($dominios));
$idEmpleado = $this->EmpleadoModel->save($save);
if ($idEmpleado != 0) {
$this->load->model('USRModel');
if( empty($usr_open) || strcasecmp($usr_open, 'No tiene')==0){
$usr_open = 'Sin OPEN';
}
if( empty($usr_oda) || strcasecmp($usr_oda, 'No tiene')==0){
$usr_oda = 'Sin ODA';
}
if( empty($usr_webclient) || strcasecmp($usr_webclient, 'No tiene')==0){
$usr_webclient = 'Sin WEBCLIENT';
}
if( empty($usr_qflow) || strcasecmp($usr_qflow, 'No tiene')==0){
$usr_qflow = 'Sin QFLOW';
}
if( empty($siv) || strcasecmp($siv, 'No tiene')==0){
$siv = 'Sin SIV';
}
$usr = array('idempleado'=>$idEmmpleado,'usr_open'=>strtoupper($usr_open),'usr_oda'=>strtoupper($usr_oda),'usr_webclient'=>strtoupper($usr_webclient),'usr_qflow'=>strtoupper($usr_qflow),'siv'=>strtoupper($siv));
$idUSR = $this->USRModel->save($usr);
if ($idUSR != 0) {
echo '<script>alert("Se han registrado todos los datos")</script>';
return false;
}else {
return true;
}
}else {
return false;
}
}
and the result that this keeps saving the values but still showing the error
A: The solution was funny, i change the ajax for a form post, and the values are send perfectly :)
<?php echo form_open('empleadoController/save_empleado', $create_form); ?>
| |
doc_23535903
|
Thanks
A: Switch to the Java perspective (you are currently in the 'Resource' perspective): Window->Open Perspective->Java (you may need to select from the Other dialog box).
If you don't see Java as an option, you may have downloaded Eclipse classic, rather than Eclipse for Java Developers.
A: Could you try to close and restart eclipse ? Also, make sure you have the sdk plugin installed correctly.
A: Is the Android SDK properly installed?
Was Eclipse restarted after that?
You can also download a Android Developer Bundle that contains all what you need (Eclipse, ADT) except JDK.
A: What could be happening is that your buttons are simply not visible, it's just matter of adding them to your toolbar. Just right click on your toolbar and hit Customize, On the Tool Bar Visibility tab make sure Android SDK and AVD Manager is selected. That should do the trick.
| |
doc_23535904
|
It's not letting me submit as the code/comment ratio is not below the threshold. hopefully now.
body {
background-color: grey;
}
p {
top: 50%;
position: relative;
}
.eye-outline {
width: 600px;
height: 350px;
background-color: black;
border-radius: 50%;
position: relative;
}
.eye-white {
width: 580px;
height: 330px;
background-color: white;
border-radius: 50%;
position: relative;
top: 3%;
left: 1.8%;
}
.iris-outline {
width: 325px;
height: 325px;
border-radius: 50%;
background-color: black;
position: relative;
left: 23%;
bottom: 97%;
}
.iris {
width: 300px;
height: 300px;
background-color: blue;
bottom: 186.5%;
left: 25%;
border-radius: 50%;
position: relative;
}
.pupil {
width: 150px;
height: 150px;
border-radius: 50%;
background-color: black;
left: 20%;
top: -20%;
position: relative;
}
<a href="index.html">back</a>
<main>
<h1>eye</h1>
</main>
<div class="eye-outline">
<div class="eye-white"></div>
<div class="iris-outline"></div>
<div class="iris"></div>
</div>
<div class="pupil"></div>
A:
refactored your code, now it won't have repeated code, and not hard-coded left, top. (everything is centered automatically)
for responsive example, see next snippet (not this below)
body {
background-color: grey;
}
.eye-outline,
.eye-white,
.iris,
.pupil,
.iris-outline {
border-radius: 50%;
}
.eye-outline {
position: relative;
}
/* the most important part, centering correctly */
.eye-white,
.iris,
.pupil,
.iris-outline {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.eye-outline,
.iris-outline,
.pupil {
background-color: black;
}
.eye-outline {
width: 600px;
height: 350px;
}
.eye-white {
width: 580px;
height: 330px;
background-color: white;
}
.iris-outline {
width: 325px;
height: 325px;
}
.iris {
width: 300px;
height: 300px;
background-color: blue;
}
.pupil {
width: 150px;
height: 150px;
}
/* not important, only debugging purposes */
body {
display: grid;
place-items: center;
min-height: 100vh;
margin: 0;
}
<div class="eye-outline">
<div class="eye-white"></div>
<div class="iris-outline"></div>
<div class="iris"></div>
<div class="pupil"></div>
</div>
responsive example
here I changed the px to vmin making the project 100% responsive!
body {
background-color: grey;
}
.eye-outline,
.eye-white,
.iris,
.pupil,
.iris-outline {
border-radius: 50%;
}
.eye-outline {
position: relative;
}
/* the most important part, centering correctly */
.eye-white,
.iris,
.pupil,
.iris-outline {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.eye-outline,
.iris-outline,
.pupil {
background-color: black;
}
/* for finding this vmin values
1. get your px values
2. divide px value by 100 (px/100)
3. add 20 to the vmin value
> so the max width is 80vmin and all other are smaller (I suggest maximum 95vmin, if you want to add 30)
*/
.eye-outline {
width: 80vmin;
height: 55vmin;
}
.eye-white {
width: 78vmin;
height: 53vmin;
background-color: white;
}
.iris-outline {
width: 52.5vmin;
height: 52.5vmin;
}
.iris {
width: 50vmin;
height: 50vmin;
background-color: blue;
}
.pupil {
width: 35vmin;
height: 35vmin;
}
/* not important, only debugging purposes */
body {
display: grid;
place-items: center;
min-height: 100vh;
margin: 0;
}
<div class="eye-outline">
<div class="eye-white"></div>
<div class="iris-outline"></div>
<div class="iris"></div>
<div class="pupil"></div>
</div>
mobile:
small height device:
desktop:
| |
doc_23535905
|
A: I stumbled upon the same problem not too long ago. I solved the problem by making the Carousel component's width larger than the carousel item itself. That way the navigation button will come outside of the item as it's item will have less width thatn its parent. Just make sure to align the Carousel and its item to center.
<Carousel className={styles.carousel}>
<Item className={styles.item} />
</Carousel>
// Inside your css
.carousel{
width: 1200px;
margin: 0 auto;
}
.item{
width: 1000px;
margin: 0 auto;
}
I don't think my solution is optimal but it's a quick fix for the given issue.
A: I know its to late but I have faced same problem. This answer can help someone.
import React, { useRef } from 'react';
import Carousel from 'react-material-ui-carousel'; // Carousel library
You can control carousel next/previous from outside button click using useRef
const sliderRef = useRef(null);
<Carousel
ref={ sliderRef }
>
<div>1</div>
<div>2</div>
<div>3</div>
</Carousel>
Then you can use onClick event on any Button
const handlePrevSlide = (e) => {
e.preventDefault();
if(sliderRef?.current){
sliderRef.current.prev();
}
}
const handleNextSlide = (e) => {
e.preventDefault();
if(sliderRef?.current){
sliderRef.current.next();
}
}
It Works great for me
| |
doc_23535906
|
if ( $the_query->have_posts() ) {
$counter = 0;
while ( $the_query->have_posts() ) {
$counter++;
$the_query->the_post();
if ($counter % 1 == 0) {
$output .= '1 - ' . $counter . '<br />------------<br />';
} elseif ($counter % 2 == 0) {
$output .= '2 - ' . $counter . '<br />------------<br />';
} elseif ($counter % 3 == 0) {
$output .= '3 - ' . $counter . '<br />------------<br />';
}
}
}
I am seeng this when I run it thoughh..
1 – 1
————
1 – 2
————
1 – 3
————
Can anyone tell me why I am seeing these results? I was expecting to see the echo 1 2 and 3 be output for the 1st second and third row.
A: Every time you divide an integer by one there is no remainder!
Therefore the line
if ($counter % 1 == 0)
is always true!
A: Because it always satisfy first condition:
// no matter what value is $counter , it always satisfy that the given value is always divisible by 1 and hence remainder will be 0
if ($counter % 1 == 0) {
$output .= '1 - ' . $counter . '<br />------------<br />';
``
That's why it don't go for other conditions
| |
doc_23535907
|
www.mysystem.com -> This request is handled by the default controller of a specific module in my system.
But when the user come to access his store, he will use the URL: storename.mysystem.com. (There are many different store names)
I would like to know where in Yii can I find the config to set wich module/controller will handle this request.
Thank you.
A: Here is my config for Yii2
main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
$host = (!empty($_SERVER['HTTP_HOST']))?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME'];
$segments = explode('.',$host);
defined('SUBDOMAIN') or define('SUBDOMAIN', strtolower($segments[0]));
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [
SUBDOMAIN => [
'class' => 'backend\modules\\'.SUBDOMAIN.'\\'.ucfirst(SUBDOMAIN),
],
],
'components' => [
'request' => [
'csrfParam' => '_csrf-backend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the backend
'name' => 'advanced-backend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'db' => [
'tablePrefix' => SUBDOMAIN.'_',
],
'urlManager'=>[
'rules' => [
'<controller:[\w-]+>/<id:\d+>' => ''.SUBDOMAIN.'/<controller>/view',
'<controller:[\w-]+/<action:[\w-]+>' => ''.SUBDOMAIN.'/<controller>/<action>',
'<controller:[\w-]+>/<action:[\w-]+>/<id:\d+>' => ''.SUBDOMAIN.'/<controller>/<action>',
],
],
],
'params' => $params,
];
| |
doc_23535908
|
class MyHandler(webapp2.RequestHandler):
def post(self):
my_file = self.request.POST['agreement']
default_bucket = app_identity.get_default_gcs_bucket_name()
gcs_filename = '/%s/%s' % (default_bucket, my_file.filename)
with gcs.open(gcs_filename, 'w', content_type=my_file.type) as f:
f.write(my_file.value)
which works fine with latin names. But if user uploads file with Cyrillic characters, I get the following error:
u'\u0410'
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__
return handler.dispatch()
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~myappid/1.385593846880232980/myapp.py", line 307, in post
with gcs.open(gcs_filename, 'w', content_type=my_file.type) as f:
File "libs/cloudstorage/cloudstorage_api.py", line 91, in open
filename = api_utils._quote_filename(filename)
File "libs/cloudstorage/api_utils.py", line 94, in _quote_filename
return urllib.quote(filename)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib.py", line 1263, in quote
return ''.join(map(quoter, s))
KeyError: u'\u0410'
How should I fix that?
Upd. I've tried to apply urllib.quote() to my_file.filename, it works almost OK, but GCS files are stored with non-readable names like %25D1%2581%25D0%25BA%25D1%2580%25D0%25B8%25D0%25BD%25D1%2588%25D0%25BE%25D1%2582.
| |
doc_23535909
|
So far this is what I've done:
*
*Created a SSL Certificate. I followed the first part of this this tutorial to create the certificate.
*I imported the server.crt file into chrome.
*Removed the semicolon in front of ;extension=php_openssl.dll in php.ini (reference)
*Edited my httpd-vhosts.conf file based on this page. The relevant section of that file is below. This is the full file: http://pastebin.com/k6Jh2eR6
<VirtualHost *>
DocumentRoot "C:\Users\user_name\Documents\project_one"
ServerName project_one.localhost
SSLEngine on
SSLCertificateFile "conf/ssl.crt/server.crt"
SSLCertificateKeyFile "conf/ssl.key/server.key"
<Directory "C:\Users\user_name\Documents\project_one">
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
I would usually access my project by typing in http://project_one.localhost
When trying to access my project by typing https://project_one.localhost into chrome I automatically get forwarded to https://project_one.localhost/xampp/ (as if XAMPP doesn't recognize https://project_one.localhost as a subdomain at all and treats it as if I'm typing in https://localhost) Any idea where I'm screwing up?
NOTE:
*
*LoadModule ssl_module modules/mod_ssl.so was uncommented in httpd.conf file
A: This may be an old question, but i am putting my answer here anyway for future reference
i'm Using XAMPP 3.2.1, Compiled May,7 2013
to enable VirtualHost with SSL at the same time here is what i did. (I'm using windows 7)
*
*your windows HOST file must already be setup
*Go to httpd-ssl.conf located at xampp\apache\conf\extra
I just copied the _default_ virtualhost and added my config. I removed all comments for shorter one and pasted this just below the default virtualHost just change the DocumentRoot and servername then Restart apache.
<VirtualHost *:443>
DocumentRoot "***path/to/your/project}***"
ServerName ***yourdomain***
ServerAdmin admin@example.com
ErrorLog "C:/xampp/apache/logs/error.log"
TransferLog "C:/xampp/apache/logs/access.log"
SSLEngine on
SSLCertificateFile "conf/ssl.crt/server.crt"
SSLCertificateKeyFile "conf/ssl.key/server.key"
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory "C:/xampp/apache/cgi-bin">
SSLOptions +StdEnvVars
</Directory>
BrowserMatch "MSIE [2-5]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
CustomLog "C:/xampp/apache/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
A: SSL, of the HTTPS://url.here/ variety, is entirely handled by Apache and has nothing to do with PHP, or any of PHP's extensions/modules, or any php.ini settings.
A typical SSL Enabled VirtualHost looks like this and contains at least these parts...
<VirtualHost *:443>
DocumentRoot "C:/WampDeveloper/Websites/www.example.com/webroot"
ServerName www.example.com
ServerAlias example.com
SSLEngine On
SSLCertificateFile "C:/WampDeveloper/Websites/www.example.com/certs/public.crt"
SSLCertificateKeyFile "C:/WampDeveloper/Websites/www.example.com/certs/private.key"
<Directory "C:/WampDeveloper/Websites/www.example.com/webroot">
Options All
AllowOverride All
order allow,deny
allow from all
</Directory>
</VirtualHost>
(The paths above are from my WampDeveloper Pro set up, Xampp's will be slightly different)
Your <VirtualHost *> line is faulty. It needs a port number, which is always 443 for an HTTPS:// URL, in combination with either an IP address or a star before it. And if using a star, also a NameVirtualHost *:443 line...
NameVirtualHost *:80
NameVirtualHost *:443
<VirtualHost *:80>
DocumentRoot "C:\xampp\htdocs"
ServerName localhost
</VirtualHost>
<VirtualHost *:443>
DocumentRoot "C:\Users\user_name\Documents\project_one"
ServerName project_one.localhost
SSLEngine on
SSLCertificateFile "conf/ssl.crt/server.crt"
SSLCertificateKeyFile "conf/ssl.key/server.key"
<Directory "C:\Users\user_name\Documents\project_one">
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:\Users\user_name\Documents\project_two"
ServerName project_two.localhost
<Directory "C:\Users\user_name\Documents\project_two">
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
A: Which version of Apache are you using ? NameVirtualHost is not available in 2.4 version.
Uncomment the line Include conf/extra/httpd-ssl.conf in httpd.conf and add the following contents (fix the paths according to xampp's path). This will enable https://localhost
<IfModule ssl_module>
Listen 443
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl .crlss phrase on stdout.
SSLPassPhraseDialog builtin
SSLSessionCache "shmcb:E:/PROGRA\~1/AMPPS/apache/logs/ssl_scache(512000)"
SSLSessionCacheTimeout 300
Mutex default
<VirtualHost _default_:443>
DocumentRoot "E:/Program Files/AMPPS/www"
ServerName localhost:443
ServerAdmin you@127.0.0.1
ErrorLog "E:/Program Files/AMPPS/apache/logs/ssl_error.log"
TransferLog "E:/Program Files/AMPPS/apache/logs/ssl_access.log"
SSLEngine on
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile "E:/Program Files/AMPPS/apache/conf/ssl_crt/server.crt"
#SSLCertificateFile "E:/Program Files/AMPPS/apache/conf/server-dsa.crt"
SSLCertificateKeyFile "E:/Program Files/AMPPS/apache/conf/ssl_key/server.key"
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory "E:/Program Files/AMPPS/www/cgi-bin">
SSLOptions +StdEnvVars
</Directory>
BrowserMatch ".*MSIE.*" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
CustomLog "E:/Program Files/AMPPS/apache/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
</IfModule>
If you want other domain like project_one.localhost have secured http connection then add the following virtualhost in httpd.conf or httpd-vhosts.conf(must be included in httpd.conf)
<IfModule ssl_module>
<VirtualHost 127.0.0.1:443>
<Directory "e:/program files/ampps/www/project_one.localhost">
Options FollowSymLinks Indexes
AllowOverride All
Order deny,allow
allow from All
</Directory>
ServerName project_one.localhost
ServerAlias project_one.localhost
ScriptAlias /cgi-bin/ "e:/program files/ampps/www/project_one.localhost/cgi-bin/"
DocumentRoot "e:/program files/ampps/www/project_one.localhost"
SSLEngine on
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile "E:\Program Files\AMPPS/apache/conf/ssl_crt/project_one.localhost.crt"
SSLCertificateKeyFile "E:\Program Files\AMPPS/apache/conf/ssl_key/project_one.localhost.key"
ErrorLog "E:/Program Files/AMPPS/apache/logs/project_one.localhost_ssl_error.log"
TransferLog "E:/Program Files/AMPPS/apache/logs/project_one.localhost_ssl_access.log"
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory "e:/program files/ampps/www/project_one.localhost/cgi-bin/">
SSLOptions +StdEnvVars
</Directory>
BrowserMatch ".*MSIE.*" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
CustomLog "E:/Program Files/AMPPS/apache/logs/project_one.localhost_ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
</IfModule>
Note : You will have to add an entry in hosts file 127.0.0.1 project_one.localhost
A: Here is simple step.
*
*Go to C:\xampp\apache\conf
Open httpd.conf
And enable the ssl extensions (Remove # from line)
LoadModule ssl_module modules/mod_ssl.so
*Go to C:\xampp\apache\conf\extra
Open httpd-vhosts.conf
Add new virtual hosts or edit existing
<VirtualHost *:443>
DocumentRoot "C:/xampp/htdocs/PROJECTNAME"
ServerName www.pl.f24sdev.com
<Directory C:/xampp/htdocs/PROJECTPATH>
AllowOverride All
Order Deny,Allow
Allow from all
</Directory>
SSLEngine on
SSLCertificateFile "conf/ssl.crt/server.crt"
SSLCertificateKeyFile "conf/ssl.key/server.key"
</VirtualHost>
A: # to use ssl
<VirtualHost *:443>
DocumentRoot "D:/xampp/htdocs/httpsProject"
DirectoryIndex index.php
SSLEngine on
SSLCertificateFile "conf/ssl.crt/server.crt"
<Directory "D:/xampp/htdocs/httpsProject"
Options All
AllowOverride All
Require all grated
</Directory>
</VirtualHost>
| |
doc_23535910
|
Stack Trace:
TESTING TRANSACTION FAILURE
Connecting to database at jdbc:mysql://localhost:3306/northwind ...
Connecting...
Checking for transaction support...
Beginning a transaction...
Looking up customer 'ACJO' ...
Connecting to database at jdbc:mysql://localhost:3306/northwind ...
Connecting...
select * from customers where CustomerID = ?
Found customer.
Adding a new order to the database...
> insert into orders(OrderDate) values(?)
> select OrderID from orders where OrderDate = ?
Updating an order...
> update orders set orders.BadField = ? where orders.OrderID = ?
**** Rolling back transaction ****
java.sql.SQLException: Unknown column 'orders.BadField' in 'field list'
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1997)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1167)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1278)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2247)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1371)
at advanced.jdbc.northwind.TransactionDemo.updateOrderMistake(TransactionDemo.java:281)
at advanced.jdbc.northwind.TransactionDemo.testTransactionFailure(TransactionDemo.java:216)
at advanced.jdbc.northwind.TransactionDemo.main(TransactionDemo.java:425)
CODE:
public void testTransactionFailure() {
System.out.println("\n\nTESTING TRANSACTION FAILURE");
Connection connection = null;
try {
connection = getConnection();
System.out.println("Checking for transaction support...");
// TODO 04. Get the database metadata.
DatabaseMetaData databaseMetadata = connection.getMetaData();
// TODO 05. Determine if the database supports transactions.
boolean supported = false;
supported = databaseMetadata.supportsTransactions();
if (supported) {
System.out.println("Beginning a transaction...");
// TODO 06. Begin database transaction.
connection.setAutoCommit(false);
// create a new customer
String companyName = "ACME Products Ltd.";
String contactName = "John Doe";
String customerID = createCustomerID(contactName, companyName);
// check for customer before inserting
if (!customerExists(customerID)) {
addCustomer(customerID, companyName, contactName);
}
// add the order
int orderID = insertOrder(connection, customerID);
// oops, forgot shipping city so let's update it
updateOrderMistake(connection, orderID, "Timbuktu");
// TODO 07. Complete the transaction.
System.out.println("Committing");
connection.commit();
} else {
System.err.println("Transactions not supported!");
}
} catch (SQLException e) {
if (connection != null) {
System.out.println("**** Rolling back transaction ****");
// TODO 08. Roll back the transaction.
try {
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
e.printStackTrace();
} finally {
try {
if (connection != null) {
// TODO 09. Release resources.
connection.close();
connection = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| |
doc_23535911
|
In the code below, goal seek is set to 40. but when i need the goal I have to change the number manually. i am expecting some extension that will require a goal seeking number each time I run the macro. Any idea please ?
'
' Run_DIO Macro
'
' Keyboard Shortcut: Ctrl+q
'
ActiveCell.GoalSeek Goal:=40, ChangingCell:=ActiveCell.Offset(-4, -1).Range( _
"A1")
ActiveCell.Offset(-3, -1).Range("A1").Select
Selection.Copy
ActiveCell.Offset(-1, 0).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveCell.Offset(4, 2).Range("A1").Select
End Sub
A: Sure... just add a variable:
Dim iGoal As Integer
iGoal = InputBox("Enter Goal")
ActiveCell.GoalSeek Goal:=iGoal, ChangingCell:=ActiveCell.Offset(-4, -1).Range( _
"A1")
Just hope they enter a number or you will get an error.
if you have it in a loop, get the input before the loop starts:
Dim iGoal As Integer
iGoal = InputBox("Enter Goal")
' code to start loop goes here
ActiveCell.GoalSeek Goal:=iGoal, ChangingCell:=ActiveCell.Offset(-4, -1).Range( "A1")
' also the rest of the code you want to loop goes here
' code to end loop goes here
| |
doc_23535912
|
Is there however a way to get separate lat and lng like you would with latLng.lat(), latLng.lng() or would I have to use something like regex to split it to lat and lng?
I am currently only able to get co-ordinates like this:
var coordinates = Event.feature.getGeometry().get();
A: The .get() function returns a LatLng*, so you should be able to call .lat() and .lng() directly on it, or .toString() or any of the LatLng methods, e.g. this should work:
var coordinates = Event.feature.getGeometry().get();
var lat = coordinates.lat();
var lng = coordinates.lng();
| |
doc_23535913
|
125011 90300
762 72816
None 55512
7156 14892
75162 8825
How would I extract the count for None? I'd expect the result to be 55512.
I've tried
>>> df.loc[df.index.isin(['None'])]
>>> Series([], Name: prod_code, dtype: int64)
and also
>>> df.loc['None']
>>> KeyError: 'the label [None] is not in the [index]'
A: It seems you need None, not string 'None':
df.loc[df.index.isin([None])]
df.loc[None]
EDIT:
If need check where NaN in index:
print (s1.loc[np.nan])
#or
print (df[pd.isnull(df.index)])
Sample:
s = pd.Series(['90300', '90300', '8825', '8825', '8825', None, np.nan])
s1 = s.value_counts(dropna=False)
print (s1)
8825 3
90300 2
NaN 2
dtype: int64
print (s1[pd.isnull(s1.index)])
NaN 2
dtype: int64
print (s1.loc[np.nan])
2
print (s1.loc[None])
2
EDIT1:
For stripping whitespaces:
s = pd.Series(['90300', '90300', '8825', '8825', '8825', 'None ', np.nan])
print (s)
0 90300
1 90300
2 8825
3 8825
4 8825
5 None
6 NaN
dtype: object
s1 = s.value_counts()
print (s1)
8825 3
90300 2
None 1
dtype: int64
s1.index = s1.index.str.strip()
print (s1.loc['None'])
1
A: Couple of things
*
*pd.Series([None] * 2 + [1] * 3).value_counts() automatically drops the None.
*pd.Series([None] * 2 + [1] * 3).value_counts(dropna=False) converts the None to np.NaN
That tells me that your None is a string. But since df.loc['None'] didn't work, I suspect your string has white space around it.
Try:
df.filter(regex='None', axis=0)
Or:
df.index = df.index.to_series().str.strip().combine_first(df.index.to_series())
df.loc['None']
All that said, I was curious how to reference np.NaN in the index
s = pd.Series([1, 2], [0, np.nan])
s.iloc[s.index.get_loc(np.nan)]
2
| |
doc_23535914
|
I have tried every possible resource and I just can't understand why I can't get this. Please help me.
A: Because who needs homework, right? It doesn't help you learn or anything.
var totalHotdogs = 525 * 3;
console.log('Total hotdog packs: ' + Math.ceil(totalHotdogs / 10));
console.log('Hotdogs remaining: ' + totalHotdogs % 10);
console.log('Total bun packs: ' + Math.ceil(totalHotdogs / 8));
console.log('Buns remaining: ' + totalHotdogs % 8);
| |
doc_23535915
|
tableComments
| postID | commentLikes |
+-----------+--------------+
| 233 | 2 |
| 233 | 0 |
| 675 | 2 |
| 345 | 12 |
| 345 | 8 |
In my PHP code, I am passing the PostID variable to my function.
I want to get the number of likes for each post based on postID passed into the function so I will need the WHERE clause.
I have tried using COUNT and GROUP BY but still no luck. So I need to count each time the postID matches a value and then add up the total number of likes. How can I do this?
A: If you're passing a single postID you don't need a group by clause, you just need to use it in the where clause and sum the likes:
SELECT SUM(likes)
FROM tableComments
WHERE postId = ?
The "?" should of course be bound from the PHP code.
A: You don't need a GROUP BY since you will filter the records passed on the POstId you are passing.Just do a summation on the records you will get the desired results.
SELECT SUM(commentLikes)
FROM comments
WHERE postID=@PostID
| |
doc_23535916
|
The journal I want to submit my paper to only accepts .tiff (doesn't work with LaTeX), .jpg (not suitable for graphs), and .eps (which doesn't work with alpha transparency, unless I rasterize the image, which leads to huge file sizes). Many of my plots use seaborn's regplot, which plots transparent confidence intervals. Is it possible to plot non-transparent CIs without completely re-doing all of my graphs manually (e.g. as dashed lines or a solid color in the background)?
Example:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("ticks")
np.random.seed(0)
n = 50
fig, ax = plt.subplots(figsize=(8,6))
x = np.random.randn(n)
y1 = np.random.randn(n)
y2 = np.random.randn(n)
sns.regplot(x, y1, ax=ax)
sns.regplot(x, y2, ax=ax)
plt.show()
What would be the easiest / best way to save this as an .eps file without losing information from the overlapping confidence intervals?
A: The problem is that you need transparency to show the two confidence intervals overlapping. One would need to rasterize the image.
I don't actually see the problem of using jpg if the journal accepts it. You may control the quality of the image using
plt.savefig(__file__+".jpg", quality=95)
Using eps is also possible, here, instead of rasterizing everything, you may rasterize only the confidence interval fill_between-curves. The advantange is that the axes, labels and points are still vecor graphics and won't look pixelated on different zoom levels.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection as p
import seaborn as sns
sns.set_style("ticks")
np.random.seed(0)
n = 50
fig, ax = plt.subplots(figsize=(8,6))
x = np.random.randn(n)
y1 = np.random.randn(n)
y2 = np.random.randn(n)
sns.regplot(x, y1, ax=ax)
sns.regplot(x, y2, ax=ax)
plt.savefig(__file__+".jpg", quality=95)
for c in ax.findobj(p):
c.set_zorder(-1)
c.set_rasterized(True)
#everything on zorder -1 or lower will be rasterized
ax.set_rasterization_zorder(0)
plt.savefig(__file__+".eps")
plt.savefig(__file__+".png")
plt.show()
The final eps file looks like this:
While the filesize is of course a bit larger, I'm not sure if this is a real problem.
| |
doc_23535917
|
I used to debug .NET framework dumps using WinDBG, without any issues, but with a dump coming from an Azure App Service there is something weird: both the clr.dll and the coreclr.dll are loaded inside the process..
As a result, using the correct version of SOS from WinDBG (the one from the dotnet core sdk installation path on my Azure VM), shows the following error when running !dumpheap:
0:000> !dumpheap
Error requesting GC Heap data
Unable to build snapshot of the garbage collector state
I tried to publish my App Service locally, as self-contained or framework-dependent, and run the published binaries. There is ONLY the .NET Core Runtime (coreclr.dll) loaded in the process, as my project targets .NET Core 2.1.
Once deployed to Azure, the binaries are ran by IIS, using the w3wp process. Is this process injecting some dependencies in my app service that require .NET Framework? Why my .NET Core 2.1 app running on Azure has some dependency with .NET Framework?
When analyzing the dump file (using ClrMD), there is two runtimes present inside:
*
*.NET Core (mscordaccore_X86_X86_4.6.26212.01.dll)
*.NET Framework (mscordacwks_X86_X86_4.7.2563.00.dll)
Tested scenarios (that did not work):
*
*Opening 32bits dump of a framework-dependent deployed app on Azure using WinDBG v10 (from Win10 SDK)
*Opening 32bits dump of a framework-dependent deployed app on Azure using WinDBG Preview v1.0.1805.17002
*Opening 64bits dump of a self-contained depoyed app on Azure (from Win10 SDK) using WinDGB Preview v1.0.1805.17002
What is working (almost):
*
*DebugDiag can analyze the dump and show some information about the heap (so it 's able to read it somehow)
*I managed to read the dump with ClrMD using custom C# code, but not all objects seems present when I browse the heap (some objects shown by DebugDiag are not visible when I browse the heap manually).
Nevertheless, I need to be able to read the dump with WinDGB to find a potential memory leak. It's been hours that I'm working on it and can't find any solution.
Any help would be greatly appreciated! :)
A: Had a similar issue and fixed it by running these commands.
You are correct in that windbg is using the wrong CLR (wrong as in not the net core app). You can prove this by running command .cordll and seeing the runtime files used path.
Tell debugger what dotnet runtime to use
.cordll -I coreclr -lp "D:\Program Files (x86)\dotnet\shared\Microsoft.NETCore.App\2.1.1"
Unload and reload CLR debugging modules
.cordll -ve -u -I coreclr -l
| |
doc_23535918
|
A: It is not simple to reuse the restart dialog so you would be better of writing your own that replicates the dialog.
Use
PlatformUI.getWorkbench().restart();
to restart Eclipse.
| |
doc_23535919
|
I want to be able to launch job on these machines, terminate a job (kill), monitor what is running on each machine.
I am looking for a framework (preferably in Java) which I can use to implement this solution.
I have looked at using the underlying components that frameworks like Hadoop or Akka use but have not come up with anything satisfactory.
A few additional constraints on what I'm looking for:
*
*It should have reasonable proliferation into production grade projects
*It should allow me to launch UNIX processes written in arbitrary languages
*It should be open source
*It should be lightweight -- An answerer has suggested I look at agent based frameworks -- though these satisfy the requirements I've posted -- I've found them to be very heavy weight. I'm looking for something that really fulfills the stated requirements and does not require me to adopt a more comprehensive methodology.
Thanks.
A: It's called multi-agent system and there are several frameworks available that you can use:
*
*JADE
*Janus
*Ascape
*Cougar
*JIAC
*Boris
*Swarm
| |
doc_23535920
|
I have used the facebook code that fb has given, but it shows nothing but the login button. I want to check if user is already logged in or not.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'<br/>Thanks for logging in, ' + response.name + '<br/>User Id: '+ response.id + '<br/>Email Id: '+ response.email + '!';
//window.location.replace('abc.html');
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
A: Your code is not the same as the facebook code I found published here. It is close but a couple keys differences and things to note. More of your file would be very helpful here. Please make sure that you have recieved and App ID from Facebook for your application and registered it. But to be clear, it seems like you are checking the login status at the wrong time. This is simply a function and we have no idea where it is called or if it mimicks the flow on the link I provided goes like this (even though this is not how they are organized within the code facebook has given). Also the only way you would see something is if you have a HTML text item with id='status'. All of this I cannot tell by your code.
*
*Initialize FB SDK and do all proper setup
*User presses login which executes this code:
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
*The above code gives you the regular scope provided by facebook (to get any more scope you have to go through a request process from facebook, just FYI). As you can see once this button is pressed and the action described as onlogin is complete we will execute the function checkLoginState() which is:
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
*This gets the logon "state" and then calls the function statusChangeCallback(response) :
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
*Now the above code, IF CONNECTED, will call your testAPI() function which will pull down the response. And it will try to find an HTML document with the id status, if you didn't create this it won't display anything.
If you are sure that you did all these steps and did them correctly, then I recommend putting a couple console.log() statements and looking at the Google Chrome console or Javascript console in your browser and seeing what state you are in and that your functions are actually being called.
If you are not sure, please double check the Facebook Login page. It is good documentation.
| |
doc_23535921
|
This works:
CREATE TABLE Student
(
Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
Name VARCHAR(50),
Grade VARCHAR(5),
Created_Date DATETIME DEFAULT GETDATE()
)
INSERT INTO Student (Name, Grade)
VALUES ( 'Uma', 'A+')
SELECT Top 1 * FROM Student
DROP TABLE Student
GO
This doesn't work:
CREATE TABLE Student
(
Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
Name VARCHAR(50),
Grade VARCHAR(5),
Created_Date DATETIME DEFAULT GETDATE()
)
INSERT INTO Student
VALUES ( 'Uma', 'A+') -- without column names
SELECT Top 1 * FROM Student
DROP TABLE Student
GO
I know that a table can have only one identity column but when I am able to insert default GETDATE() without even passing date column name. What could be the logical reason to pass the column names to insert statement when I have date column as default?
A: If you don't specify the columns, then you are implicitly stating you are inserting values into all the columns, and thus must define those values. A DEFAULT value is only used if you explicitly state DEFAULT in the VALUES clause or omit the column entirely from the INTO clause.
As such INSERT INTO Student VALUES... is equivalent to INSERT INTO Students ([Name], Grade, Created_Date) VALUES... and in the above, you don't provide a value for Created_Date so the statement fails.
If you really don't want to include the columns (which is ill-advised) use DEFAULT in the VALUES clause:
INSERT INTO Student
VALUES ( 'Uma', 'A+',DEFAULT)
| |
doc_23535922
|
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'ENGINE=FEDERATED' at line 35
CREATE TABLE users AS (
SELECT
ID, user_email, user_registered,
first_name.meta_value as first_name,
last_name.meta_value as last_name,
telephone.meta_value as telephone,
country.meta_value as country,
company.meta_value as company,
address.meta_value as address,
city.meta_value as city,
professional_title.meta_value as professional_title,
state.meta_value as state,
areas_of_interest.meta_value as areas_of_interest
FROM wp_users
LEFT JOIN wp_usermeta AS first_name ON first_name.user_id=ID
AND first_name.meta_key='first_name'
LEFT JOIN wp_usermeta AS last_name ON last_name.user_id=ID
AND last_name.meta_key='last_name'
LEFT JOIN wp_usermeta AS telephone ON telephone.user_id=ID
AND telephone.meta_key='telephone'
LEFT JOIN wp_usermeta AS country ON country.user_id=ID
AND country.meta_key='country'
LEFT JOIN wp_usermeta AS company ON company.user_id=ID
AND company.meta_key='company'
LEFT JOIN wp_usermeta AS address ON address.user_id=ID
AND address.meta_key='address'
LEFT JOIN wp_usermeta AS city ON city.user_id=ID
AND city.meta_key='city'
LEFT JOIN wp_usermeta AS professional_title ON professional_title.user_id=ID
AND professional_title.meta_key='professional_title'
LEFT JOIN wp_usermeta AS state ON state.user_id=ID
AND state.meta_key='state'
LEFT JOIN wp_usermeta AS areas_of_interest ON areas_of_interest.user_id=ID
AND areas_of_interest.meta_key='areas_of_interest'
) ENGINE=FEDERATED DEFAULT CHARSET=latin1 CONNECTION "*****";
Note: FEDERATED Engine is on and working on other non-joined table.
A: Short answer:
CREATE statements for FEDERATED tables require an additional piece of data called the CONNECTION. Not having that data in your statement is the source of the syntax error.
Long answer:
For this particular instance, a VIEW would be a better tool than a FEDERATED table.
The FEDERATED storage engine can be though of kind of like symbolic linking in Linux or shortcuts in Windows. It is primarily used to access a table on a server that doesn't actually store the table locally, but on a different mysql server. For that reason, when you create a FEDERATED table, you also have to include the CONNECTION that the FEDERATED storage engine should use in the CREATE statement. You can opt to create a FEDERATED table on the same host that the data is stored, but it'll result in additional overhead caused by the unnecessary steps taken to access local data. Please see this link for more details.
A VIEW, on the other hand, is like a stored query that executes whenever you query the VIEW table. This page can give you more information on it.
| |
doc_23535923
|
1) Automatic memory management
2) Separation of concerns
Usually constructors have a few parameters that are objects of the framework, but I can't put them in the interfaces.
My question is, if I'm using interfaces to make a separation of concern of the classes that implements them, why my code ends up binded still to the concrete class that implements the interface to call the constructor and its parameters.. and
What's the merit of putting the creator code in a factory method? (something I'm still not using..)
Thanks!
=== EDIT ===
The point in my question are the constructor's paremeters.. In the framework lots of objects needs a few other to work.. The answers adress well the point of separation of concerns, but still I don't see how the solve the problem of parameters..
If I don't go the constructor way, I should go the "procedure Initialize" way (in the interface) and "CheckObjectInitialized" (protected) in every method of the object.. how this will be cleaner?
A: The Factory method will allow you to register implementors of your interfaces in a single place and allow the rest of your code to "just ask for an implementor."
Factory.GetImplementorOf(IMyInterface)
which then returns an interface reference.
It is up to you how you want to implement the factory. You could create new instances for every interface requested, maintain a pool of already created instances and return references to those, or do a mix depending on the interface requested.
You can also decide whether you want your factory to allow multiple implementors of the same interface (how do you select the right one then) or enforce a single implementor for every interface, or a mix.
Multiple instances can come in handy for example when dealing with duplicate(d) services that maybe unavailable at times so you can pick one that happens to be up.
It may also be an idea to provide a GetImplementorOf(array of Interfaces). So you can have multiple implementors of IDump but distinguish amongst them by the way they dump information: for example an implementor that IDump's an object to IHTML format.
are factories prepared to work with constructors parameters in some
clean way??
Well now, that is an interesting question. No, in and of themselves they are not. Factories usually work with a standard constructor perhaps taking an "Owner" and/or "Id" parameter.
If you want more specific constructors on a per class base, you have to
*
*create more factories, which defeats the purpose of having a single point to register implementors of interfaces
*allow for initialization methods on a per interface/class basis that should be called immediately after construction, which opens up your code to forgetfullness and makes classes less immutable.
*or come up with a way to incorporate constructor signature knowledge into the factory.
At one stage I chose the third option. By creating a factory that
*
*required registration of an interface with abstract base class
*required implementors to descend from the abstract base class
*returned implementors as a metaclass reference instead of an instance
TFactory = class(...)
public
procedure RegisterInterface(const aGUID: TGUID; const aAbstractBase: TClass);
procedure RegisterImplementor(const aGUID: TGUID; const aImplementor: TClass);
function GetImplementor(const aGUID: TGUID): TClass;
Drawbacks:
*
*It is quite a drag to have to declare both an interface and an abstract base class.
*It defeats the "multiple inheritance by interface" advantage of interfaces in a single inheritance language.
*You need to spread knowledge of the interface/abstract base class pair throughout your code otherwise you still can't use the class specific constructors. Generics might help here but I haven't yet looked into that.
*It serves no real purpose if you do not have multiple implementors of the same (set of) interfaces.
*Even if you want multiple implementors just for unit testing, it seems overkill. I have found dummy classes declared in the test unit with the relevant parts of the class's interface to be more helpful and effective.
All in all I have gone back to the standard constructor / specific Initialization pair method. It should be fairly easy to write a code scanning unit test to check that every GetImplementor call from the factory is followed by an Initialization call. And though the class in theory is no longer as immutable as it would be with a specific constructor, it still is for all practical purposes. And if you want to ensure that the Initialize method is only called right after construction, that should be easy to add.
A: Interfaces don't remove the need for there to be implementing objects. Every single interface you use has to have an implementing object. So your code needs to call constructors.
Factory patterns and other creational patterns allow you to make the object creation more flexible and modular. These creational patterns allow you to hide all your implementing class declarations, e.g. by putting them in the implementation section of the units.
Without using methods to abstract interface creation, your goal no. 2 will be incomplete.
A: If you are feeling the need to add constructors to your interfaces, you are doing something wrong.
Interfaces are simply a declaration of functionality. How that functionality gets provided is of no concern to the interface. Indeed, how the implementing objects are created should be of absolutely no concern to the consumer of an interface. This is where Dependency Injection comes in.
Dependency Injection is the notion that the implementation of your interfaces is completely decoupled from the code actually using the interface. It is more than a factory class (as deftly describe by Marjan) in that it allow you to completely decouple the declaration and implementation of an implementing class from the interface.
Thus, when you declare an interface, a Dependency Injection container can create/fetch an instance of the implemented object automatically, removing the need for you to even create it. In this way, your application becomes merely a wiring together of interfaces without any concern for construction of anything. Your library code is revealed only through the DI container.
The Delphi Spring Framework provides a very nice DI Container for you to use. You can find the Delphi Spring Framework and the Spring Container here:
http://code.google.com/p/delphi-spring-framework/
A: Nick Hodges presentation at CodeRage simply stated that you should move the job of construction to a class which has as its sole responsibility, the creation of objects. This is often called the "factory" pattern.
From a logical perspective, this makes sense to me as a specific instance of the 'S' in the SOLID principles; Single Responsibility. Creation of objects should be a single responsibility (the factory), as should linking of objects together to solve a problem (composition of one real object plus five mocked ones, would be a unit test, or composition of five real objects to solve a real problem in the production codebase).
| |
doc_23535924
|
adding code snippet:
Parent.tsx
export default observer(function Parent(){
const [allowPanelToClose,setAllowPanelToClose]= useState(true);
const UpdateSidepanelClose = function (allowClose:boolean)
{
if(allowClose !== undefined)
{
setAllowPanelToClose(allowClose)
}
}
return(
<Child allowSidepanelToClose = {UpdateSidepanelClose}
isSidepanelCloseAllowed ={allowPanelToClose}/>
);
})
Child.tsx
export interface ChildProps{
allowSidepanelToClose : (allowClose: boolean) => void;
isSidepanelCloseAllowed : boolean;
}
function Child({
allowSidepanelToClose,
isSidepanelCloseAllowed}:ChildProps){
useKeypress("Escape",() =>{
if(isSidepanelCloseAllowed === false) // isSidepanelCloseAllowed is coming as true which is issue
{
// do something
}
}
const onBlur = (event: any)=>{
if (!event.currentTarget.contains(event.relatedTarget))
{
const isValid = somefunction();
}
if(isvalid)
{
// perform some operation
}
else{
allowSidepanelToClose(false);//set parent state from true to false
}
}
}
A: Pass down the state and the setter, so the foo and setFoo. If the child calls setFoo, foo will also be updated.
Also, you should include snippets of your current code when asking a question.
| |
doc_23535925
|
Hopefully someone can help me on this topics.
| |
doc_23535926
|
So my Card class is fairly simple. It creates a Card object with the parameters suit,value, and isFaceUp. All is good here.
Then I create the CardStack class which represents a stack of class.There are 4 types: 's' - stock, 'w' - waste, 'f' - foundations, and 't' - tableau.
It is supposed to have the following. I also included a private field "type" in the object and a getter and setter for it.
public class CardStack extends Stack {
private char type;
public char getType() {
return type;
}
public void setType(char type) {
this.type = type;
}
public CardStack(char type) {
this.setType(type);
Stack<Card> Stack = new Stack<Card> ();
}
public void pushes(Card newCard) {
this.push(newCard);
}
public Card pops() {
this.pop();
return null;
}
public boolean isEmpty() {
return this.empty();
}
public int size() {
return capacityIncrement;
}
However I feel like this is too easy and wrong. Does that make sense?
Now here is what we are supposed to do for the actual meat of the game.
1."you should have an array of stacks that represent the tableau stacks, an array of stacks that represent the foundation stacks, and 2 individual stacks that represent the stock and waste stacks respectively"
Why do we need an array of stacks? Why isn't one stack enough? Is this what my professor wants?
static CardStack[] tableau;
static CardStack[] foundation;
static CardStack waste = new CardStack('w');
static CardStack stock = new CardStack('s');
Then we create a main stack of the 52 cards which I did like this
static Card[] mainStack = new Card[53];
for (int i = 1; i < 13; i++) {
for (int j = 1; j < 4; j++) {
mainStack[i * j] = new Card(i, j, true);
}
}
I think that part is right.
Ok then "move all 52 cards from the game stacks into the deck stack. Then, shuffle the deck by using the static method shuffle() in the Collections class "
Here is where I get caught up. The mainstack is an Array of Card that has 52 cards in it. The deck stack is a stack which is not an array. How do I put the array into the stack and then how do I use the method shuffle on a stack. Isn't the shuffle method only for arrays?
There is a bunch more but I guess that's enough for now
A:
Why do we need an array of stacks? Why isn't one stack enough?
Think about the way the game is played. You have a foundation which is 7, IIRC, stacks of foundation cards. You also have 4 stacks for the table that you're working your cards to. Then of course you have single stacks of cards for the waste and stock.
Is this what my professor wants?
They may be the only one to truly answer that question, but it looks good to me.
How do I put the array into the stack and then how do I use the method
shuffle on a stack. Isn't the shuffle method only for arrays?
You can push elements onto the stack, but I wouldn't shuffle the stack. It's not in the wheel-house of functionality for a stack. If you put them in and then shuffled them, your expected order no longer exists. Shuffle the array, then distribute the cards in the appropriate stacks in the same manner in which one would deal the game.
| |
doc_23535927
|
Of course I could implement this in my settings pane as well. Though this doesn't make a lot of sense in my opinion: The user might get confused, wondering, what is the correct setting?
So does anyone know, how to disable "use cellular data" by default?
Thanks!
A: There is no API to change that value. You could try to teach the user how to do it or as you mentioned, build the setting inside your app.
| |
doc_23535928
|
I don't want it to be stretched - I want it to scale it to 100% - the image will be scaled to fit 900x900, and the part of the image that is out of bounds will be cropped.
I've tried this code:
UIGraphicsBeginImageContextWithOptions(newSize, true, UIScreen.main.scale);
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage!
But all it does is stretching the image to fit 900x900 size, that's not what I want.
Any idea what can I do here?
Thanks
A: If I'm reading your question correctly, you can achieve what you want by tailoring the contentMode property of a UIImageView (which you attach your image to).
Take a look at the developer reference here : https://developer.apple.com/reference/uikit/uiimageview
However, to answer your question, to put the image in the center of a UIImageView without stretching it, use contentMode.center ; to scale it to fit the view but maintain the aspect ratio use .aspectFit ; and to stretch to fit the image view use .scaleToFill. There are other options explained in the link.
A: You can crop from center of the image to 900 pixel if the image size is larger than 900.
Here is the code :
func centerCropImage(image1:UIImage) -> UIImage
{
let modifiedSize:CGFloat = 900.0;
// Center the crop area
let clippedRect = CGRect(x: ((image.size.width - modifiedSize)/2), y: ((image.size.height - modifiedSize)/2), width: modifiedSize, height: modifiedSize);
// Crop logic
let imageRef:CGImage = image.cgImage!.cropping(to: clippedRect)!;
//(image as! CGImage).cropping(to: clippedRect)!;
let croppedImage = UIImage(cgImage: imageRef);
return croppedImage;
}
Hope it helps
Happy coding ...
| |
doc_23535929
|
I have created partition like this
$tomorrow = strtotime("tomorrow midnight");
$partition = date('dmy',$tomorrow);
ALTER TABLE `stats`
ADD PARTITION (
PARTITION p_$partition VALUES LESS THAN ($tomorrow)
)";
Then I do this to get daily partition
ALTER TABLE `stats`
PARTITION BY RANGE (`date`) (
PARTITION p_$partition VALUES LESS THAN ($tomorrow)
)
Now I need to merge all partition up till today into single partition doing this way
ALTER TABLE `stats` REORGANIZE PARTITION
p_190416,p_200416.....
INTO (
PARTITION p_$partition VALUES LESS THAN ($tomorrow)
);
But its showing me error as
Fatal error: Reorganize of range partitions cannot change total ranges except for last partition where it can extend the range in
Please see and suggest any possible way to do this without loosing data.
| |
doc_23535930
|
C:\>ping 192.168.1.1 -n 1
Pinging 192.168.1.1 with 32 bytes of data:
Reply from 192.168.1.1: bytes=32 time=3ms TTL=64
Ping statistics for 192.168.1.1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 3ms, Maximum = 3ms, Average = 3ms
C:\>echo %errorlevel%
0
C:\>ping 192.168.1.105 -n 1
Pinging 192.168.1.105 with 32 bytes of data:
Reply from 192.168.1.102: Destination host unreachable.
Ping statistics for 192.168.1.105:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
C:\>echo %errorlevel%
0
Is there any way to do it with ping or any other build-in-Windows tool? I would prefer not to install anything if that's possible...
A: Next code snippet should work:
set "_ip=localhost"
set "_ip=192.168.1.1"
ping %_ip% -n 1 -4 | find /i "TTL=">nul
if errorlevel 1 (
echo ping %_ip% failure
) else (
echo ping %_ip% success
)
*
*-4 to force using IPv4 (as e.g. ping localhost replies IPv6 with no TTL= output)
*| find /i "TTL=" as find command raises errorlevel well
*>nul to suppress undesired output
A: Do something like this:
PING 192.168.1.1 -n 1 | FIND /I "Reply from "
Then you can check errorlevel
Edit: To accommodate "Destination host unreachable error you could do this:
PING 192.168.1.1 -n 1 | FIND /I /V "unreachable" | FIND /I "Reply from "
A: I think tracert is what you need.Sets errorlevel on 1 if cant find the host.And should use the same port as ping.-h 2 is to reduce wait time ,as the complete route is not needed.
tracert -h 2 somehost.com >nul 2>nul && (
echo reachable host
) || (
echo unreachable host
)
EDIT: to print correct errorlevel in the brackets you need delayed expansion.Here's more advanced example :
@echo off
setlocal enableDelayedExpansion
echo checking google.com
tracert -h 1 google.com >nul 2>nul && (
echo reachable host
echo !errorlevel!
rem prevent execution of negative condition
color 22
) || (
echo unreachable host
echo !errorlevel!
)
echo checking asdasdjjakskwkdhasdasd
tracert -h 1 asdasdjjakskwkdhasdasd >nul 2>nul && (
echo reachable host#
echo !errorlevel!
rem prevent execution of negative condition
color
) || (
echo unreachable host#
echo !errorlevel!
)
| |
doc_23535931
|
A: If you mean "I want to get the wikitext only", then look at the wikipedia.Page class, and the get method.
import wikipedia
site = wikipedia.getSite('en', 'wikipedia')
page = wikipedia.Page(site, 'Test')
print page.get() # '''Test''', '''TEST''' or '''Tester''' may refer to:
#==Science and technology==
#* [[Concept inventory]] - an assessment to reveal student thinking on a topic.
# ...
This way you get the complete, raw wikitext from the article.
If you want to strip out the wiki syntax, as is transform [[Concept inventory]] into Concept inventory and so on, it is going to be a bit more painful.
The main reason for this trouble is that the MediaWiki wiki syntax has no defined grammar. Which makes it really hard to parse, and to strip. I currently know no software that allows you to do this accurately. There's the MediaWiki Parser class of course, but it's PHP, a bit hard to grasp, and its purpose is very very different.
But if you only want to strip out links, or very simple wiki constructs use regexes:
text = re.sub('\[\[([^\]\|]*)\]\]', '\\1', 'Lorem ipsum [[dolor]] sit amet, consectetur adipiscing elit.')
print text #Lorem ipsum dolor sit amet, consectetur adipiscing elit.
and then for piped links:
text = re.sub('\[\[(?:[^\]\|]*)\|([^\]\|]*)\]\]', '\\1', 'Lorem ipsum [[dolor|DOLOR]] sit amet, consectetur adipiscing elit.')
print text #Lorem ipsum DOLOR sit amet, consectetur adipiscing elit.
and so on.
But for example, there is no reliable easy way to strip out nested templates from a page. And the same goes for Images that have links in their comments. It's quite hard, and involves recursively removing the most internal link and replacing it by a marker and start over. Have a look at the templateWithParams function in wikipedia.py if you want, but it's not pretty.
A: There is a module called mwparserfromhell on Github that can get you very close to what you want depending on what you need. It has a method called strip_code(), that strips a lot of the markup.
import pywikibot
import mwparserfromhell
test_wikipedia = pywikibot.Site('en', 'test')
text = pywikibot.Page(test_wikipedia, 'Lestat_de_Lioncourt').get()
full = mwparserfromhell.parse(text)
stripped = full.strip_code()
print full
print '*******************'
print stripped
Comparison snippet:
{{db-foreign}}
<!-- Commented out because image was deleted: [[Image:lestat_tom_cruise.jpg|thumb|right|[[Tom Cruise]] as Lestat in the film ''[[Interview With The Vampire: The Vampire Chronicles]]''|{{deletable image-caption|1=Friday, 11 April 2008}}]] -->
[[Image:lestat.jpg|thumb|right|[[Stuart Townsend]] as Lestat in the film ''[[Queen of the Damned (film)|Queen of the Damned]]'']]
[[Image:Lestat IWTV.jpg|thumb|right|[[Tom Cruise]] as Lestat in the 1994 film ''[[Interview with the Vampire (film)|Interview with the Vampire]]'']]
'''Lestat de Lioncourt''' is a [[fictional character]] appearing in several [[novel]]s by [[Anne Rice]], including ''[[The Vampire Lestat]]''. He is a [[vampire]] and the main character in the majority of ''[[The Vampire Chronicles]]'', narrated in first person.
==Publication history==
Lestat de Lioncourt is the narrator and main character of the majority of the novels in Anne Rice's ''The Vampire Chronicles'' series. ''[[The Vampire Lestat]]'', the second book in the series, is presented as Lestat's autobiography, and follows his exploits from his youth in France to his early years as a vampire. Many of the other books in the series are also credited as being written by Lestat.
*******************
thumb|right|Stuart Townsend as Lestat in the film ''Queen of the Damned''
'''Lestat de Lioncourt''' is a fictional character appearing in several novels by Anne Rice, including ''The Vampire Lestat''. He is a vampire and the main character in the majority of ''The Vampire Chronicles'', narrated in first person.
Publication history
Lestat de Lioncourt is the narrator and main character of the majority of the novels in Anne Rice's ''The Vampire Chronicles'' series. ''The Vampire Lestat'', the second book in the series, is presented as Lestat's autobiography, and follows his exploits from his youth in France to his early years as a vampire. Many of the other books in the series are also credited as being written by Lestat.
A: You can use wikitextparser. For example:
import pywikibot
import wikitextparser
en_wikipedia = pywikibot.Site('en', 'wikipedia')
text = pywikibot.Page(en_wikipedia,'Bla Bla Bla').get()
print(wikitextparser.parse(text).sections[0].plain_text())
will give you:
"Bla Bla Bla" is a song written and recorded by Italian DJ Gigi D'Agostino. It heavily samples the vocals of "Why did you do it?" by British band Stretch. It was released in May 1999 as the third single from the album, L'Amour Toujours. It reached number 3 in Austria and number 15 in France. It was sampled in the song "Jump" from Lupe Fiasco's 2017 album Drogas Light.
A: Pywikibot is able to remove any wikitext or html tags. There are two functions inside textlib:
*
*removeHTMLParts(text: str, keeptags=['tt', 'nowiki', 'small', 'sup']) -> str:
Return text without portions where HTML markup is disabled but keeps text between html tags. For example:
from pywikibot Import textlib
text = 'This is <small>small</small> text'
print(removeHTMLParts(text, keeptags=[]))
this will print:
This is small text
*removeDisabledParts(text: str, tags=None, include=[], site=None) -> str:
Return text without portions where wiki markup is disabled. This removes text inside wikitext text. For example:
from pywikibot Import textlib
text = 'This is <small>small</small> text'
print(removeDisabledPartsParts(text, tags=['small']))
this will print:
This is text
There are a lot of predefined tags to be removed or to be kept like
'comment', 'header', 'link', 'template';
default for tags parameter is ['comment', 'includeonly', 'nowiki', 'pre', 'syntaxhighlight']
Some other examples:
removeDisabledPartsParts('See [[this link]]', tags=['link']) gives 'See '
removeDisabledPartsParts('<!-- no comments -->', tags=['comment']) gives ''
removeDisabledPartsParts('{{Infobox}}', tags=['template']) gives '', but works only for Pywikibot 6.0.0 or higher
| |
doc_23535932
|
test1=# select * from sample order by created_at DESC;
id | status | service | created_at
----+--------+---------+---------------------
8 | OK | 1 | 2015-09-16 11:54:00
7 | OK | 1 | 2015-09-16 11:53:00
6 | FAIL | 1 | 2015-09-16 11:52:00
5 | OK | 1 | 2015-09-16 11:51:00
How can I select only the rows with ID 7 and 8. Using window functions I can get row numbers partitioned over status, but so far did not figure out the way how to limit the results only to the last rows identifying 'successful period' for given service.
A: The most simple approach would be this:
SELECT *
FROM sample AS s
LEFT JOIN (SELECT service, max(id)
FROM sample
WHERE status = 'FAIL'
GROUP BY service) AS q
ON s.id > q.id
AND s.service = q.service
A: You need to find the time of the most recent status = 'FAIL' for each service, then select those records of the same service that are more recent:
SELECT *
FROM sample
LEFT JOIN (
SELECT service, max(created_at) AS last_fail
FROM sample
WHERE status = 'FAIL'
GROUP BY service) f USING (service)
WHERE created_at > last_fail
OR last_fail IS NULL; -- also show services without ever failing
This assumes there are only two status codes. If there are more, add a status = 'OK' filter to the WHERE clause.
| |
doc_23535933
|
Use .corr to get the correlation between two columns
here is my code:
import pandas as pd
df = pd.DataFrame({'a':[1, 1, 1, 1], 'b':[1, 1, 1, 1]})
print(df)
cor = df['a'].corr(df['b'])
print('the correlation:')
print(cor)
here is the result (dataframe two columns of 1):
a b
0 1 1
1 1 1
2 1 1
3 1 1
the correlation:
nan
I am expecting correlation to be 1, but it is nan. Why is this the case and how do i correct this ?
A: It appears as though there is zero correlation here, and this would work with a different set of numbers.
so this would return a number:
import pandas as pd
df = pd.DataFrame({'a':[1, 2, 3, 4], 'b':[1, 2, 3, 4]})
print(df)
cor = df['a'].corr(df['b'])
print('the correlation:')
print(cor)
returns 1
| |
doc_23535934
|
For a beginner and non-java programmer, it's beyond my capability to solve this.
Will anyone be kind enough to take a look of the error logging to see what's going wrong?
Thanks in advance!
The error reads
INFO [main] 2022-09-29 02:04:13,705 QueryProcessor.java:180 - Preloaded 0 prepared statements
INFO [main] 2022-09-29 02:04:13,705 StorageService.java:628 - DSE version: 6.7.8
INFO [main] 2022-09-29 02:04:13,705 StorageService.java:635 - CQL supported versions: 3.4.5 (default: 3.4.5)
INFO [main] 2022-09-29 02:04:13,706 StorageService.java:637 - Native protocol supported versions: 3/v3, 4/v4, 5/v5-beta, 65/dse-v1, 66/dse-v2 (default: 66/dse-v2)
INFO [main] 2022-09-29 02:04:13,869 MessagingService.java:631 - Starting Messaging Service on /192.168.3.211:7000 (eth1)
WARN [main] 2022-09-29 02:04:13,875 SystemKeyspace.java:1531 - No host ID found, created d2e5e12e-2904-4273-82a6-2f9157d9a53f (Note: This should happen exactly once per node).
INFO [main] 2022-09-29 02:04:13,882 YamlConfigurationLoader.java:77 - Configuration location: file:/etc/dse/cassandra/cassandra.yaml
INFO [main] 2022-09-29 02:04:13,888 YamlConfigurationLoader.java:77 - Configuration location: file:/etc/dse/cassandra/cassandra.yaml
INFO [main] 2022-09-29 02:04:13,888 StorageService.java:551 - Unable to gossip with any peers but continuing anyway since node is in its own seed list
INFO [main] 2022-09-29 02:04:13,891 YamlConfigurationLoader.java:77 - Configuration location: file:/etc/dse/cassandra/cassandra.yaml
INFO [main] 2022-09-29 02:04:13,894 YamlConfigurationLoader.java:77 - Configuration location: file:/etc/dse/cassandra/cassandra.yaml
INFO [main] 2022-09-29 02:04:13,899 YamlConfigurationLoader.java:77 - Configuration location: file:/etc/dse/cassandra/cassandra.yaml
INFO [main] 2022-09-29 02:04:13,921 StorageService.java:809 - Loading persisted ring state
INFO [main] 2022-09-29 02:04:13,921 StorageService.java:938 - Starting up server gossip
INFO [main] 2022-09-29 02:04:13,936 YamlConfigurationLoader.java:77 - Configuration location: file:/etc/dse/cassandra/cassandra.yaml
INFO [main] 2022-09-29 02:04:13,947 YamlConfigurationLoader.java:77 - Configuration location: file:/etc/dse/cassandra/cassandra.yaml
INFO [main] 2022-09-29 02:04:13,962 Gossiper.java:2181 - Waiting for gossip to settle before accepting client requests...
INFO [main] 2022-09-29 02:04:34,104 Gossiper.java:2250 - No gossip backlog
INFO [main] 2022-09-29 02:04:34,104 Gossiper.java:2301 - No pending echos; proceeding. Echos failed 0, Echos succeeded 0
INFO [main] 2022-09-29 02:04:34,104 Gossiper.java:2311 - Gossip settled; proceeding
INFO [main] 2022-09-29 02:04:34,112 YamlConfigurationLoader.java:77 - Configuration location: file:/etc/dse/cassandra/cassandra.yaml
INFO [main] 2022-09-29 02:04:34,116 YamlConfigurationLoader.java:77 - Configuration location: file:/etc/dse/cassandra/cassandra.yaml
INFO [main] 2022-09-29 02:04:34,116 StorageService.java:1012 - This node will not auto bootstrap because it is configured to be a seed node.
INFO [main] 2022-09-29 02:04:34,118 YamlConfigurationLoader.java:77 - Configuration location: file:/etc/dse/cassandra/cassandra.yaml
INFO [main] 2022-09-29 02:04:34,123 BootStrapper.java:287 - Generated random tokens. tokens are {1026191633272881870, 2416632423410724679, 2093892847431908356, -4548202942808601697, -1119126112187310335, 5578049864412509280, -531931717796690256, -1731479975960449539}
INFO [main] 2022-09-29 02:04:34,144 MigrationManager.java:179 - Create new Keyspace: KeyspaceMetadata{name=system_traces, kind=REGULAR, params=KeyspaceParams{durable_writes=true, replication=ReplicationParams{class=org.apache.cassandra.locator.SimpleStrategy, replication_factor=2}}, tables=[system_traces.sessions, system_traces.events], views=[], functions=[], types=[]}
ERROR [MemtablePostFlush:1] 2022-09-29 02:04:34,255 ColumnFamilyStore.java:972 - Unexpected exception running post flush task
java.util.concurrent.ExecutionException: java.lang.AssertionError: Invalid argument: point:-1223185043
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.cassandra.db.ColumnFamilyStore.lambda$switchMemtable$0(ColumnFamilyStore.java:968)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.cassandra.concurrent.NamedThreadFactory.lambda$threadLocalDeallocator$0(NamedThreadFactory.java:79)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:750)
Caused by: java.lang.AssertionError: Invalid argument: point:-1223185043
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder$DataHolder.wrap(StreamingTombstoneHistogramBuilder.java:314)
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder$DataHolder.addValue(StreamingTombstoneHistogramBuilder.java:201)
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder.flushValue(StreamingTombstoneHistogramBuilder.java:132)
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder$Spool.forEach(StreamingTombstoneHistogramBuilder.java:476)
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder.flushHistogram(StreamingTombstoneHistogramBuilder.java:126)
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder.build(StreamingTombstoneHistogramBuilder.java:152)
at org.apache.cassandra.io.sstable.metadata.MetadataCollector.finalizeMetadata(MetadataCollector.java:267)
at org.apache.cassandra.io.sstable.format.SSTableWriter.finalizeMetadata(SSTableWriter.java:286)
at org.apache.cassandra.io.sstable.format.SSTableWriter.statsMetadata(SSTableWriter.java:295)
at org.apache.cassandra.io.sstable.format.trieindex.TrieIndexSSTableWriter.openFinal(TrieIndexSSTableWriter.java:375)
at org.apache.cassandra.io.sstable.format.trieindex.TrieIndexSSTableWriter.access$700(TrieIndexSSTableWriter.java:70)
at org.apache.cassandra.io.sstable.format.trieindex.TrieIndexSSTableWriter$TransactionalProxy.doPrepare(TrieIndexSSTableWriter.java:420)
at org.apache.cassandra.utils.concurrent.Transactional$AbstractTransactional.prepareToCommit(Transactional.java:168)
at org.apache.cassandra.io.sstable.format.SSTableWriter.prepareToCommit(SSTableWriter.java:254)
at org.apache.cassandra.io.sstable.SimpleSSTableMultiWriter.prepareToCommit(SimpleSSTableMultiWriter.java:100)
at org.apache.cassandra.db.ColumnFamilyStore$Flush.flushMemtable(ColumnFamilyStore.java:1278)
at org.apache.cassandra.db.ColumnFamilyStore$Flush.run(ColumnFamilyStore.java:1194)
... 5 common frames omitted
ERROR [main] 2022-09-29 02:04:34,342 CassandraDaemon.java:853 - Exception encountered during startup
java.util.concurrent.CompletionException: java.util.concurrent.ExecutionException: java.lang.AssertionError: Invalid argument: point:-1223185043
at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:292)
at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:308)
at java.util.concurrent.CompletableFuture.biRelay(CompletableFuture.java:1300)
at java.util.concurrent.CompletableFuture$BiRelay.tryFire(CompletableFuture.java:1284)
at java.util.concurrent.CompletableFuture$CoCompletion.tryFire(CompletableFuture.java:1034)
at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:488)
at java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:1990)
at org.apache.cassandra.db.ColumnFamilyStore.lambda$switchMemtable$0(ColumnFamilyStore.java:974)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.cassandra.concurrent.NamedThreadFactory.lambda$threadLocalDeallocator$0(NamedThreadFactory.java:79)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:750)
Caused by: java.util.concurrent.ExecutionException: java.lang.AssertionError: Invalid argument: point:-1223185043
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.cassandra.db.ColumnFamilyStore.lambda$switchMemtable$0(ColumnFamilyStore.java:968)
... 5 common frames omitted
Caused by: java.lang.AssertionError: Invalid argument: point:-1223185043
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder$DataHolder.wrap(StreamingTombstoneHistogramBuilder.java:314)
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder$DataHolder.addValue(StreamingTombstoneHistogramBuilder.java:201)
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder.flushValue(StreamingTombstoneHistogramBuilder.java:132)
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder$Spool.forEach(StreamingTombstoneHistogramBuilder.java:476)
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder.flushHistogram(StreamingTombstoneHistogramBuilder.java:126)
at org.apache.cassandra.utils.streamhist.StreamingTombstoneHistogramBuilder.build(StreamingTombstoneHistogramBuilder.java:152)
at org.apache.cassandra.io.sstable.metadata.MetadataCollector.finalizeMetadata(MetadataCollector.java:267)
at org.apache.cassandra.io.sstable.format.SSTableWriter.finalizeMetadata(SSTableWriter.java:286)
at org.apache.cassandra.io.sstable.format.SSTableWriter.statsMetadata(SSTableWriter.java:295)
at org.apache.cassandra.io.sstable.format.trieindex.TrieIndexSSTableWriter.openFinal(TrieIndexSSTableWriter.java:375)
at org.apache.cassandra.io.sstable.format.trieindex.TrieIndexSSTableWriter.access$700(TrieIndexSSTableWriter.java:70)
at org.apache.cassandra.io.sstable.format.trieindex.TrieIndexSSTableWriter$TransactionalProxy.doPrepare(TrieIndexSSTableWriter.java:420)
at org.apache.cassandra.utils.concurrent.Transactional$AbstractTransactional.prepareToCommit(Transactional.java:168)
at org.apache.cassandra.io.sstable.format.SSTableWriter.prepareToCommit(SSTableWriter.java:254)
at org.apache.cassandra.io.sstable.SimpleSSTableMultiWriter.prepareToCommit(SimpleSSTableMultiWriter.java:100)
at org.apache.cassandra.db.ColumnFamilyStore$Flush.flushMemtable(ColumnFamilyStore.java:1278)
at org.apache.cassandra.db.ColumnFamilyStore$Flush.run(ColumnFamilyStore.java:1194)
... 5 common frames omitted
INFO [StorageServiceShutdownHook] 2022-09-29 02:04:44,346 DseDaemon.java:855 - DSE shutting down...
INFO [StorageServiceShutdownHook] 2022-09-29 02:04:44,347 PluginManager.java:491 - Deactivating plugins which do not require native transport
INFO [StorageServiceShutdownHook] 2022-09-29 02:04:44,347 PluginManager.java:501 - Deactivation of plugins which do not require native transport finished
INFO [StorageServiceShutdownHook] 2022-09-29 02:04:48,761 MessageServer.java:130 - internode-messaging message server finished shutting down.
INFO [StorageServiceShutdownHook] 2022-09-29 02:04:52,772 MessageServer.java:130 - internode-messaging message server finished shutting down.
INFO [StorageServiceShutdownHook] 2022-09-29 02:04:52,773 HintsService.java:222 - Paused hints dispatch
WARN [StorageServiceShutdownHook] 2022-09-29 02:04:52,774 Gossiper.java:1978 - No local state, state is in silent shutdown, or node hasn't joined, not announcing shutdown
INFO [StorageServiceShutdownHook] 2022-09-29 02:04:52,774 MessagingService.java:754 - Waiting for messaging service to quiesce
INFO [ACCEPT-/192.168.3.211] 2022-09-29 02:04:56,777 MessagingService.java:1081 - MessagingService has terminated the accept() thread
INFO [StorageServiceShutdownHook] 2022-09-29 02:04:56,820 HintsService.java:222 - Paused hints dispatch
ERROR [StorageServiceShutdownHook] 2022-09-29 02:04:56,836 AbstractCommitLogSegmentManager.java:405 - Failed to force-recycle all segments; at least one segment is still in use with dirty CFs.
INFO [StorageServiceShutdownHook] 2022-09-29 02:04:56,842 PluginManager.java:195 - Plugins are stopped.
INFO [StorageServiceShutdownHook] 2022-09-29 02:04:56,843 DseDaemon.java:934 - DSE shutdown complete.
| |
doc_23535935
|
for param_one, param_two, param_three, param_four, param_five in get_params(some_stuff_here, and_another stuff):
I have found that i can brake a for in statement only with a backslash :
for param_one, param_two, param_three, param_four, param_five \
in get_params(some_stuff_here, and_another_stuff):
But my linter has issues with this formatting , what is a Pythonic way of
formatting statements like this ?
A: You can take advantage of the implicit line joining inside parentheses (as recommended in PEP-8):
for (param_one, param_two,
param_three, param_four,
param_five) in get_params(some_stuff_here,
and_another stuff):
(Obviously, you can choose how long to make each line and whether or not you need to include line breaks in each set of parentheses.)
Looking at this 8+ years later, I would break up the long single logical line in the first place, rather than trying to split the whole thing across multiple physical lines. For example (much like @poke does),
for t in get_params(some_stuff_here,
and_other_stuff):
(param_one,
param_two,
param_three,
param_four, param_five) = t
A: all_params = get_params(some_stuff_here, and_another_stuff)
for param_one, param_two, param_three, param_four, param_five in all_params:
pass
Or you could move the target list inside the loop:
for params in get_params(some_stuff_here, and_another_stuff):
param_one, param_two, param_three, param_four, param_five = params
pass
Or combine both.
| |
doc_23535936
|
Here is my code:
long long p=19,q=14;
cout<<pow(p,q);
The correct answer is: 799006685782884121 but my code gives me 799006685782884096 which is incorrect.
I have also tried doing these calculations using unsigned long long instead of long long, but this didn't help.
A: The pow function is defined as:
double pow(double x, double y);
Which means that it takes floating point arguments and returns a floating point result. Due to the nature of floating point numbers, some numbers can not be exactly represented. The result you're getting is probably the closest match possible.
Note also that you're doing two (probably lossy) conversions:
*
*converting the arguments from long long to double, and
*converting the result of the function from double to long long.
| |
doc_23535937
|
I am not a powershell user and have very little experience with it, but I don't believe I am even using a snap in. Can anyone help me alleviate this error?
************** Exception Text ************** System.Management.Automation.Runspaces.PSSnapInException: Cannot load
Windows PowerShell snap-in Microsoft.PowerShell.Diagnostics because of
the following error: Could not load file or assembly
'Microsoft.PowerShell.Commands' or one of its dependencies. The system
cannot find the file specified. at
System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadMshSnapinAssembly(PSSnapInInfo
mshsnapinInfo) at
System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadPSSnapIn(PSSnapInInfo
mshsnapinInfo) at
System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.LoadPSSnapIns(Collection`1
mshsnapinInfos, PSConsoleLoadException& warning) at
System.Management.Automation.Runspaces.RunspaceConfigForSingleShell.CreateDefaultConfiguration()
at
System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(PSHost
host) at HPSM_Assistant.HPSMAssistant.ADuser() in
C:\Users\user\Documents\Code\HPSMAssistant\HPSMAssistant\Form1.cs:line
592 at HPSM_Assistant.HPSMAssistant.LoadTemplateEID() in
C:\Users\user\Documents\Code\HPSMAssistant\HPSMAssistant\Form1.cs:line
396 at HPSM_Assistant.HPSMAssistant.Form1_Load(Object sender,
EventArgs e) in
C:\Users\user\Documents\Code\HPSMAssistant\HPSMAssistant\Form1.cs:line
208 at System.Windows.Forms.Form.OnLoad(EventArgs e) at
System.Windows.Forms.Form.OnCreateControl() at
System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl() at
System.Windows.Forms.Control.WmShowWindow(Message& m) at
System.Windows.Forms.Control.WndProc(Message& m) at
System.Windows.Forms.Form.WmShowWindow(Message& m) at
System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg,
IntPtr wparam, IntPtr lparam)
Also System.Management.Automation - Assembly Version: 3.0.0.0 -Win32 Version: 10.0.10586.0 loads correctly. (It was installed in the c# app via Nuget.)
Here is the code I use:
private string ADuser()// create Powershell runspace and run script to Get AD current username
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser");
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("$env:UserName");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
//Create string to output
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
| |
doc_23535938
|
I'm sure I've missed something simple, but I can't find out why it doesn't work?
function addWitness() {
$.post("AddWintess", {
Witnesses: [{
LastName: "test1",
FirstName: "test1",
MiddleName: "test1"
}, {
LastName: "test2",
FirstName: "test2",
MiddleName: "test2"
}]
}, function(data) {
my.viewModel.allItems = ko.observableArray(data.Witnesses);
});
}
var my = {
viewModel: new WitnessesModel()
}
function WitnessesModel() {
var self = this;
self.allItems = ko.observableArray([]);
self.test = ko.computed(function() {
var result = "";
self.allItems().forEach(function(item) {
result += item + "; ";
});
});
}
ko.applyBindings(my.viewModel);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<ul data-bind="foreach: allItems">
<li data-bind="text: FirstName"></li>
</ul>
<input type="button" class="btn btn-success" value="+" onclick="addWitness()" />
I've set the breakpoints in the test function, but it's not getting fired.
A: Try this line my.viewModel.allItems(data.Witnesses); instead of
my.viewModel.allItems = ko.observableArray(data.Witnesses);
| |
doc_23535939
|
Added: yesterday Closing: 17.02.2013
there may be variations of the above string such as :
Added: today Closing: 04.02.2013
Added: 16.01.2013 Closing: 15.02.2013
I need to be able to get the "yesterday" and "17.02.2013" or "today" and "04.02.2013" or "16.01.2013" and "15.02.2013"
right now here is what i got..
$pieces = explode(" ", $initialDate);
echo $pieces[1]; // piece2
echo $pieces[3]; // piece2
echo '<br/><br/>';
but i get only "today" and "closing" , should have got the closing date, but its not working..
should i have done it using regex?
A: explode can be used, in this case. The keys and values come in pairs with the key preceding the value, so look for the keyword and then take the next string as the value. I'd probably return it as an array of the form (key1 =>value1, key2=>value2,)
When it works explode is likely to be faster than regex, but the speed isn't a big factor in most cases.
Edit: the example has multiple spaces between the elements, these need to be removed first or empty items skipped in the result.
A: There are too much spaces in your string to make it in the order you expect.
To keep with explode(), do not blindly address an array member with guessed number but print_r($pieces); first, then notice the right number, then use it
If the number of spaces can vary - regexp is the only [sensible] choice. Though it can be combined with regexp by using simple $pieces = preg_split('#\s#',$initialDate);
A: You can do it using regular expression
$string="Added: today Closing: 04.02.2013";
$result = preg_match_all("/([a-z A-z])*day|((\d{2}\.){2}(\d{4}))/", $string,$match);
print_r($match[0]);
output
Array ( [0] => today [1] => 04.02.2013 )
pattern "/([a-z A-z])*day/" match string ends with day
pattern "((\d{2}.){2}(\d{4}))" matches date of the form (dd.mm.yyyy) or (mm.dd.yyyy)
Live Demo
A: Exploded is just fine, as long as the input does not change. Regex are fine too, but they usually make the code hard to read and slow down the application. It seems you are missing the double-spaces in your text, that creates a empty string in your result of explode. Checkout the contents with var_dump, print_r or better use debugging.
foreach(explode("\n", $str) as $line)
print_r(explode(' ', $line));
| |
doc_23535940
|
I just want to scan all my fields in order to see which ones can return an array.
Thank you!
A: The following query allows you to retrieve documents whose array field is not empty:
POST test/_search
{
"query": {
"script": {
"script": {
"source": "doc.arr.value != null && doc.arr.size() > 0"
}
}
}
}
Note that using >=0 will also return documents with null arrays.
Detecting fields with an empty array is more complicated and cannot be achieved with a script query, because there's no different between an field containing an empty array and a field containing null.
A much better and more efficient way to achieve what you want is by adding a field at indexing time with the length of that array (e.g. called arrayLength below). That way you could use a simple range query on that field.
POST test/_search
{
"query": {
"range" : {
"arrayLength" : {
"gte" : 0
}
}
}
}
| |
doc_23535941
|
Is there a simpler way to add rows of my elements everytime I click the button? I also need to be able to delete the row when I click delete.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="top20 content-form">
<label class="col-sm-2 control-label" for="addEnv"><button class="btn btn-primary">add</button></label>
<div class="col-sm-10">
<label id="addEnv" class="label label-secondary pointer-label"><span class="fa fa-plus-circle"></span> Add environment variable</label>
<div id="envVariablesDiv">
<div class="input-group">
<span class="input-group-addon">Text</span>
<input id="msg" type="text" class="form-control" name="msg" placeholder="Additional Info">
</div>
<div class="input-group">
<span class="input-group-addon">Text</span>
<input id="msg" type="text" class="form-control" name="msg" placeholder="Additional Info">
</div>
<button class="btn btn-danger">Delete</button>
</div>
</div>
</div>
JS I done: The styling is different now. I want to use input group.
$('#addEnv').click(function () {
$('#envVariablesDiv').append('<div class="col-sm-5 top10"><label for="envName" class="control-label">Name</label><input id="envName" class="form-control" name="envName" type="text" placeholder="e.g. name1" /></div>' +
'<div class="col-sm-5 top10"><label for=envVar class="control-label">Variable</label><input class="form-control" id="envVar" type="text" name="envVar" placeholder="e.g. var1" /></div><div class="col-sm-2 top10"><button class="btn btn-danger"><span class="fa fa-trash"></span></button></div>');
});
| |
doc_23535942
|
But most of things that I've found are about IIS setting like session management. Only one thing was related to development like below.
*
*Object that will be stored on session variable should be implemented serializable.
Isn't there really anything else to be considered for web farm environment on programming level?
Anyone can help me to clear this issue?
A: The most important rule of thumb when designing an application that will run in a web farm is this application to be stateless. This means that you shouldn't be storing anything in memory.
If you application depends on Session or TempData, that's the first indication that you will have problems.
Another important aspect to take into account if you are using FormsAuthentication is to properly configure the machine keys of all nodes to use the same value. Otherwise an authentication cookie emitted by one node won't be able to be decrypted on another node and the user will be considered as non-authenticated even if he has a cookie.
A: Below is a link to a series of articles that might give you an overview of web farms in the context of IIS and .NET. The articles target audience is programmers who want to get started with web farms and the MS technologies built around them. They are targeted at IIS 7.5 and .NET 4.5 but they most likely will work fine with IIS 7.0 and .NET 4.0 as well and things should not be too different in IIS 8.0 either.
http://dotnetcodr.com/2013/06/17/web-farms-in-net-and-iis-part-1-a-general-introduction/
Also, have a look at the accepted answer for this post Make an ASP.NET MVC application Web Farm Ready
| |
doc_23535943
|
Bounce Method:
-(void)bounce {
[self jumpSound];
if (frog.center.y > 450) {
upMovement = 2;
}
else if (frog.center.y > 350) {
upMovement = 1.5;
}
else if (frog.center.y > 250) {
upMovement = 0.5;
}
}
and the lilypad movement:
-(void)lilyPadMovement {
if (CGRectIntersectsRect(frog.frame, lily.frame) && (upMovement <=-1)){
[self bounce];
[self lilyPadFall];
if (lilyPadUsed == NO) {
addedScore = 1;
lilyPadUsed = YES;
}
}
}
Essentially what I'm trying to fix is the frogs bouncing movement. When the frog lands in the middle of a lily pad and bounces it doesn't look bad, but at times the frog will simply touch the sides of the lil pad and the bounce method will be called because the rectangles intersected. I tried CGRectContainsRect but it made the game to hard, because it delayed the speed of the game. So I'm not sure how to fix it. Any suggestions?
A: You really want to know if there's a sufficient overlap to enable the frog to push off, rather than fall in the water. So maybe the distance between the centers has to be less than X, where you tune X based on what looks good.
For example ( using the Pythagorean formula) :
//having defined this function:
inline float square (float a) { return a*a; }
//change intersect test to:
if (((square(frog.center.x-lily.center.x) + square(frog.center.y-lily.center.y)) < 10000) &&
(upMovement <= -1)) { ...
| |
doc_23535944
|
https://www.kiabi.com/magasins.html
I need to scrape information from each blue bullet.
Thank you.
I tried to look into the source code and find something with "hidden" status.
A: When asking question on stackoverflow, you should take the time to explain what you have already tried, and show us the code that you produced.
Take the time to read https://stackoverflow.com/help/how-to-ask
As for your scraping question, you can get the information about all the shops with the following cURL command.
Don't remove the Referer header, as the server is using it for validation.
> curl 'https://api.woosmap.com/stores?key=woos-3246a080-0b90-39a2-a673-5ae6b9acb1d9' -H 'Referer: https://www.kiabi.com/magasins.html'
You may need to refresh the key parameter after some time.
You can find it hardcoded in the HTML of the url that you provided.
> curl -s 'https://www.kiabi.com/magasins.html' | grep -oE 'fr:woos-[0-9a-f-]{36}'
fr:woos-3246a080-0b90-39a2-a673-5ae6b9acb1d9
| |
doc_23535945
|
I have a fruit-store table and a fruit table. I have built a user interface (form) for the greengrocer (who owns a chain of such stores, and intends buying many more) so that he can easily fill in the details concerning his stores, and the fruit that can be sold in them.
Each fruit has its own unique ID, as does each store. However fruit is not limited to any particular store, but may be sold in any number.
As such there is an intermediate table storeFruit which enables a many-to-many relationship between the store and fruit.
The greengrocer wants to be able to list out the stock (which consists only of fruit) of his store as he is putting in the other details about the store, like the address and phone number. Consequently there is a field in the form to list the fruit contained within the store. The only thing it has to do in the fruit table is correlate the fruit with the relevant store.
I have created a combobox which displays a particular fruit, but the field has no bearing on any table. Indeed, if you select banana and move to the next store in the form, banana will stay in the field, highlighting how it has no bearing on the information input. I have also created a subform (fruit), but this does not allow the ability to pick from a predefined list... it will end up with lots of "unique" (as in unique Fruit_ID) apples, pears, etc, as they are merely appended to the table. fruit essentially represents a predefined list.
So how might I bind this combobox such that it updates the required fields properly, and thus alleviate the stress of my fictional flummoxed greengrocer?
PS: looking at the diagram I realise that the stock column in the store table will never actually be used due to the nature of the relationships - but I created these tables and relationship diagram on the fly without saving, as I won't ever be using them, so it's too late to rectify it now!
A: The usual way to set this up is with store in the main form and storeFruit in the subform. The link child and master fields should be set to store_ID. The_fruit_in_question becomes a combobox with a row source set to fruit ( select fruit_ID, fruit from fruit ), the bound column is 1 and the column widths are, say, 0, 2cm.
| |
doc_23535946
|
Code for server is here:
#define PORT 8080
int serverSocket = 0;
//Creating a socket, AF_INET is for IPv4
if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("Error in socket");
exit(EXIT_FAILURE);
}
//setting address
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(PORT); //htons() is for converting TCP/IP network byte order.
address.sin_addr.s_addr = INADDR_ANY;
memset(&address.sin_zero, 0, sizeof(address.sin_zero)); //IMPORTANT to clear sin_zero because of unexpected behavior!
//binding server
if (bind(serverSocket, (struct sockaddr*)&address, sizeof(address)) < 0) {
perror("Error in bind");
exit(EXIT_FAILURE);
}
//setting listen
if (listen(serverSocket, 10) < 0) {
perror("Error in listen");
exit(EXIT_FAILURE);
}
long valRead = 0;
int newSocket = 0;
int addrLen = sizeof(address);
char *send = "GET /index.html HTTP/1.1 200 OK\nContent-Type: text/html;charset=UTF-8\nContent-Length: 242\n\nindex.html";
while(1) {
printf("Waiting for a connection.\n");
if (newSocket = accept(serverSocket, (struct sockaddr*)&address, (socklen_t*)&addrLen) < 0) {
perror("Error in accept");
exit(EXIT_FAILURE);
}
char buffer[3000] = {0};
valRead = read(newSocket, buffer , sizeof(buffer));
printf("%s\n", buffer);
write(newSocket, send, strlen(send));
printf("Sent\n");
if (close(newSocket) < 0) {
perror("Error in close");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
return 0;
Terminal output:
I use browser in my VM also.
After a try to connect server is still waiting for a connection.
What can be a problem? Thanks.
A: You need parentheses here, because < has higher precedence than =:
if ((newSocket = accept(serverSocket, (struct sockaddr*)&address, (socklen_t*)&addrLen)) < 0) {
You're setting newSocket to the result of the comparison, not the descriptor returned by accept().
| |
doc_23535947
|
"Parameter is not valid"
my code is ..
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
// display content
string value1 = row.Cells[0].Value.ToString();
string value2 = row.Cells[1].Value.ToString();
label2.Text = value1;
label4.Text = value2;
//Display Image
SqlConnection cn = new SqlConnection();
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\PROJECT\\NEW\\CASTING CALCULATING SYSTEM\\CASTING CALCULATING SYSTEM\\DB_CASTING.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True;";
cn.ConnectionString = str;
SqlCommand cmd = new SqlCommand ();
cmd.Connection = cn;
string strsql = "select image from EmpMaster WHERE Fname = '" +value2+ "'";
cmd.CommandText = strsql ;
cn.Open();
SqlDataReader dr;
try
{
dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] picarr = (byte[])dr["image"];
MemoryStream ms = new MemoryStream(picarr);
ms.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(ms);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}
}
A: It is most likely a memory cap issue, see this thread for an example.
So what that says is basically that the issue is on the Image side, not your SQL. It might be different reasons than pure memory, there are many reasons the picture constructor could fail.
Also, DJ KRAZE is right, you need to do some work on your SQL queries. As a minimum use parameters (significantly reduces the risk of SQL injection attacks) and put that SqlConnection and SqlDataReader into a using block to ensure they are properly disposed.
| |
doc_23535948
|
I would like to know how it is possible to reference the foreign key of the class Scientifique in the category project since Scientifique doesn't have a primary key (it has the primary key of the parent class Personnel in my opinion).
Should I add a primary key in Scientifique?
A: It depends on what you mean by add. You would usually transform the abstract model to a more concrete database model. In that transformation you would add the foreign keys as attributes and eventually stereotype them (based on a profile) as e.g. «FK».
Alternatively you could create a schema in something like Erwin (or any ERD tool) and create the foreign keys there.
I would refrain from adding that information to the abstract model since it would simply take that importance of being abstract...
| |
doc_23535949
|
intDivByFive(N) = N/5
I have been told to define it recursively.
Can someone explain what exactly is it that I'm being asked to do here?
A: I am assuming that you want to compute N/5 recursively ... without using the / operator. (This is unnecessary and impractical, but we can ignore that in this context.)
(Note in the rest of this answer I am renaming N to be D to align with the terminology used in the JLS.)
For the Euclidian definition of the division d / n, we need to find q and r such that d = q * n + r where 0 ≤ r < |n|.
Thus, for d / 5, q can be computed by the following:
public int intDivByFive(int d) {
if (d < 0)
return intDivByFive(d + 5) - 1;
else if (d >= 5)
return intDivByFive(d - 5) + 1;
else
return 0;
}
The function above works by repeatedly adding or subtracting 5 and counting the number of times you do that. Additions are negative counts.
In theory, this works for all integers. In practice it will fail with a StackOverflowError if the magnitude of d is too large. (Java does not do tail call optimization in any existing version, at time of writing.)
HOWEVER, that's not what / means in Java. In fact the JLS definition for division is:
Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d ⋅ q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.
So the correct implementation for Java / semantics is:
public int intDivByFive(int d) {
if (d <= -5)
return intDivByFive(d + 5) - 1;
else if (n >= 5)
return intDivByFive(d - 5) + 1;
else
return 0;
}
We could debate endlessly which version is correct. But it depends on what is meant by "the mathematical function of division by 5". We don't have the context to determine that.
Since mathematicians normally1 take division to mean Euclidian division, I would argue that the first solution is more correct. However, this is semantics. The real point is that there are multiple different definitions of division.
1 - For example, my old copy of "Fundamentals of Abstract Algebra" by Neal H. McCoy (1972) uses the Euclidian definition but simply calls this division.
A: As I said, it's unnecessary to make basic arithmetic operation a recursive function.
If you want a recursive function f(n) that gives the same result as n/5, you can use something like this:
int divByFive(int n) {
if(n > -5 && n < 5) {
return 0;
}
if(n > 0) {
return 1 + divByFive(n - 5);
} else {
return -1 + divByFive(n + 5);
}
}
Just add or subtract 5 until you reach 0 (or close to 0).
| |
doc_23535950
|
.then((url) => {
if (url == null || undefined) {
return this.props.image;
} else {
const { image } = this.props;
//entryUpdate is an action creator in redux.
this.props.entryUpdate({ prop: 'image', value: url })
.then(() => {
this.setState({ loading: false });
});
but I get the following error:
How do I format setState() inside an asynchronous function that's called after an action creator?
Any help would be much appreciated!
A: In order for this to work, your action creator this.props.entryUpdate would need to return a promise for the async work it's doing. Looking at the error message, that does currently not appear to be the case.
You also need to be aware that calling setState() in the asynchronous callback can lead to errors when the component has already unmounted when the promise resolves.
Generally a better way is probably to use componentWillReceiveProps to wait for the new value to flow into the component and trigger setState then.
A: I placed the .then() function inside of the the if statement. But it should be like this:
.then((url) => {
if (url == null || undefined) {
return this.props.image;
} else {
const { image } = this.props;
this.props.entryUpdate({ prop: 'image', value: url })
}
})
.then(() => {
this.setState({ loading: false });
});
| |
doc_23535951
|
Public Shared Function GetUsersByUsername(ByVal Username As String) As ADUser
Dim myUser As New ADUser
Dim oroot As DirectoryEntry = New DirectoryEntry("GC://ldap.myCompany.com")
Dim osearcher As DirectorySearcher = New DirectorySearcher(oroot)
Dim result As SearchResult
osearcher.Filter = String.Format("(&(SAMAccountName={0}))", Username)
osearcher.PropertiesToLoad.Add("cn")
osearcher.PropertiesToLoad.Add("SAMAccountName") 'Users login name
osearcher.PropertiesToLoad.Add("givenName") 'Users first name
osearcher.PropertiesToLoad.Add("sn") 'Users last name
osearcher.PropertiesToLoad.Add("mail") 'Email address
osearcher.PropertiesToLoad.Add("accountExpires") 'expiration date
result = osearcher.FindOne
Try
Dim userPath As String() = result.Path.ToString.Split(New Char() {","c})
Dim parsedString As String
Dim User As DirectoryEntry
Dim expirationDate As String
User = result.GetDirectoryEntry()
myUser.UserID = result.Properties("cn").Item(0)
myUser.EmailAddress = result.Properties("mail").Item(0)
myUser.FirstName = result.Properties("givenName").Item(0)
myUser.LastName = result.Properties("sn").Item(0)
expirationDate = result.Properties("accountExpires").Item(0)
If (isAccountLocked(User) = True) Then
myUser.Status = ADUser.AccountStatus.Locked
ElseIf (isAccountEnabled(User) = False) Then
myUser.Status = ADUser.AccountStatus.Disabled
ElseIf (isAccountExpired(expirationDate) = True) Then
myUser.Status = ADUser.AccountStatus.Expired
Else
myUser.Status = ADUser.AccountStatus.Active
End If
parsedString = userPath((userPath.Length - 3))
myUser.Domain = parsedString.Substring(3, parsedString.Length - 3)
Catch ex As Exception
Return Nothing
End Try
Return myUser
End Function
A: works for me:
*
*Load the property:
osearcher.PropertiesToLoad.Add("lastLogon")
*Access it:
dim myDateInterval = result.Properties("lastLogon").Item(0)
Note you'll get back an interval value. It's 64-bit, unsigned, I think. There are some casting methods in .NET, but they only take signed 64-bit. Haven't checked how many years ahead that would be before it was an issue!
Also, if you use the newer UserPrincipal from DirectoryServices then it's got lastlogon in it, that returns a nullable date.
A: Have you tried the 'lastLogon' LDAP attribute? Your code looks good, I'm guessing you're just not sure where the information is stored in AD?
| |
doc_23535952
|
a(str)
b(str, str)
c(str, str, str)
d(str, str, str, str
I found that I can specify Callable[..., None] in general way but how to specify with details that all arguments will be str without doing ugly syntax Union[Callable[[str], None], Callable[[str, str], None, __more_like_this__]. Is it other method to do it? Can I do it with use typing?
A: What you want is the union of 4 distinct types.
t1 = Union[
Callable[[str],Any],
Callable[[str,str],Any],
Callable[[str,str,str],Any],
Callable[[str,str,str,str],Any],
]
Constrast that with the type of function that can accept 1 to 4 arguments:
t2 = Callable[[str,Optional[str],Optional[str],Optional[str]],Any]
A function like
def foo(x: str, y:str):
does not belong to the second type above. If I say I need a function of type t2, you don't know how many arguments I might try to pass. I could give you foo, but then you might try to pass 3 arguments, or only 1, and get a TypeError.
If you ask for a function of type t1, it's OK for me to give you foo. t1 does not promise that all values in t1 can more or less than exactly 3 arguments; it only includes values that do.
A: You could use a callback protocol to specify a function type with variadic string arguments:
from typing_extensions import Protocol
class Callback(Protocol):
def __call__(self, *args: str) -> None: ...
And use it like this:
def handler(cb: Callback) -> None:
cb('a', 'b', 'c')
def callback(*args: str) -> None:
pass
handler(callback)
Note that the callback has to take variadic arguments, e.g. this won't work:
def callback(a: str, b: str) -> None:
pass
Protocols were added in Python 3.8 to the standard library typing module, so if you want to use them on Python 3.5-3.7, you will need to install the typing-extensions module from PyPI.
| |
doc_23535953
|
'(?:' + tags + '):([\\s\\S]*?)(?=\\s+(?:' + tags + '|END):)'
..as it's a dynamic RegEx, the variable 'tags' is used for the several parameters i want to filter for.
How would the RegEx look like in PHP code?
I get the following part work:
(?:' + tags + '):([\\s\\S]*?)
But the second part wont work with PHP, no matter what I try:
(?=\\s+(?:' + tags + '|END):)
Thank you for your help!
Edit 1:
My current PHP code looks like this:
$regexp = '(?:'.$tags.'):([\\s\\S]*?)(?=\\s+(?:'.$tags.'|END):)';
Edit 2:
I'm trying to find the following tags/parameters:
$tags = 'X-WR-CALNAME|X-WR-TIMEZONE|X-WR-CALDESC|BEGIN|CLASS|DTSTAMP|UID|CREATED|LAST-MODIFIED|SEQUENCE|STATUS|TRANSP|X-MICROSOFT-CDO-BUSYSTATUS|ORGANIZER|SUMMARY|DESCRIPTION|LOCATION|DTSTART|DTEND|END';
...out of a text which looks like this:
BEGIN:VEVENT
DTSTART:20121117T143000Z
DTEND:20121117T163000Z
DTSTAMP:20121130T185808Z
UID:n3f3qjgtads37phsq3oovmvouc@google.com
CREATED:20121102T191518Z
DESCRIPTION:1. Bundesliga\, 12. Spieltag \n\nhttp://www.fussball-spielplan.
info
LAST-MODIFIED:20121117T170303Z
LOCATION:Imtech-Arena\, Hamburg
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Hamburger SV - 1. FSV Mainz 05 (1:0)
TRANSP:TRANSPARENT
END:VEVENT
..in order to get the value right next to the appropriate tag/parameter.
A: The regex seems to work when delimiters (the / at the start and end of the pattern) are added.
$regexp = '/(?:'.$tags.'):([\s\S]*?)(?=\s+(?:'.$tags.'|END):)/';
There is no need to escape the \ in php regex strings unless you are trying to match a literal "\" (in which case '\\\\' must be used) - although it is fine to do so.
| |
doc_23535954
|
Total Hours of Use of a Machine = Hours Function * Range of Functioning
where Hours Function is the hours of use of a certain machine. Take it at a cost that for each machine is a constant and Range of Functioning is the difference between the final date of the evaluation and the initial date, measured in hours.
For example, I want to measure the Total Hour Use of a Machine in between 15/10/2019 and 14/20/2019. So the math is the following:
Assume: 2 machines
Hours Function machine A: 6
Hours Function machine B: 9
Range of Functioning = 15/10/2019 - 14/10/2019 = 24 hours
The output:
Total Hours of Use of a Machine A: 144
Total Hours of Use of a Machine B: 216
I need to do that in Power BI in a way that any user moving a slicer of date, refresh the Total Hours of Use of a Machine.
I don't find any way that I can get the difference between the final date of the evaluation and the initial date and put in DAX or a new column.
A: You have to use measures if you want to recalculate the value when you change the date with a slicer.
The first step is to be sure to be able to calculate the number of day selected by your slicer.
It seems to be easy but if you use the function FirstDate on your calendar table directly integrated in PowerBI.
You'll never have what you expect.
The tricks here to get this number of day is to calculate the number of rows in your calendar table with the function countrows.
When you have this number day you just have to multiply this by 24 ( hours) and by the sum of your "Hours Function machine".( 6 for A 9 for B in your example )
( It's important to use the sum or another aggregate function like average because if you have multiple value the measure fall in error because it need only one value to multiply).
The dax formula looks like :
= COUNTROWS(('Calendar')) * Sum(Machine[Hours function])
You can then display this measure filtered by the Machine Name and a date slicer(based on your calendar table).
| |
doc_23535955
|
#app/models/diy.rb
class Diy < Activerecord::Base
#schema id | summary | created_at | updated_at
has_many :steps
end
#app/models/step.rb
class Step < ActiveRecord::Base
# schema id | step_content | photo | created_at | updated_at
belongs_to :diy
end
Is there any way to create a diy database row and associated with it step database rows in the same view?
Closest I've got is:
<%= form_for(@diy) do |f| %>
<%= f.label :summary %><br>
<%= f.text_field :summary %><br>
<%= f.label :steps %><br>
<%= f.text_field :steps %><br>
<%= f.submit %>
<% end %>
but with this code I'm not accessing any columns in step table.
If it helps to solve the problem, with this code i get "Steps" text field which is already filled with "Step::ActiveRecord_Associations_CollectionProxy:0x9613ce0".
A: class Diy < ActiveRecord::Base
has_many :steps
accepts_nested_attributes_for :steps
end
class Step < ActiveRecord::Base
belongs_to :diy
end
accepts_nested_attributes_for lets Diy take attributes for Steps:
Diy.create( steps_attributes: [{ step_content: 'Stir it.' }] )
To create the form inputs use fields_for:
<%= form_for(@diy) do |f| %>
<%= f.label :summary %><br>
<%= f.text_field :summary %><br>
<%- # wrapping it in a fieldset element is optional -%>
<fieldset>
<legend>Steps</legend>
<% f.fields_for(:steps) do |step_fields| %>
<%= step_fields.label :step_content %><br>
<%= step_fields.text_field :step_content %><br>
<% end %>
</fieldset>
<%= f.submit %>
<% end %>
What this does it iterate though @diy.steps and creates a <textarea name="diy[steps_attributes][][step_content]"> for each. step_fields is a form builder which is scoped to the particular nested record.
Note that if @diy.steps is nil like on a new record then there will be no form inputs. To solve that you need to seed the record:
class DiysController
# ...
def new
@diy = Diy.new
@diy.steps.new # creates a new step that the user can fill in.
end
def edit
@diy = Diy.find(params[:id])
@diy.steps.new # creates a new step that the user can fill in.
end
end
To avoid getting a bunch of junk steps you would use the reject_if option:
class Diy < ActiveRecord::Base
has_many :steps
accepts_nested_attributes_for :steps, reject_if: :all_blank
end
To whitelist the nested attributes in your controller use a array containing the allowed attributes:
def diy_params
params.require(:diy).permit(:summary, steps_attributes: [:step_content])
end
Please read:
*
*http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
*http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
A: To add to @Max's answer, you'll want to use the following:
#app/models/diy.rb
class Diy < Activerecord::Base
#schema id | summary | created_at | updated_at
has_many :steps
accepts_nested_attributes_for :steps
end
#app/controllers/diys_controller.rb
class DiysController < ApplicationController
def new
@diy = Diy.new
@diy.steps.build
end
def create
@diy = Diy.new diy_params
@diy.save
end
private
def diy_params
params.require(:diy).permit(steps_attributes: [:step_content])
end
end
#app/views/diys/new.html.erb
<%= form_for @diy do |f| %>
<%= f.fields_for :steps do |s| %>
<%= s.number_field :step_count %>
<% end %>
<%= f.submit %>
<% end %>
--
If you wanted to just associate new Diy's to existing Steps, you'll want to populate the step_ids (collection_singular_ids) attribute:
#controller
def diy_params
params.require(:diy).permit(step_ids: [])
end
#app/views/diys/new.html.erb
<%= form_for @diy do |f| %>
<%= f.collection_select :step_ids, Step.all, :id, :name %>
<%= f.submit %>
<% end %>
| |
doc_23535956
|
I want to modify a type and make it abstract by applying the TypeAttributes.Abstract flag, how can I do this?
I'm sure I need to call into the CLR somewhere, but I can't trace down where it gets this info from, it seems to be an endless system of layered methods calling other ones.
A: You can alter a type programatically using a library such as Mono.Cecil.
Assume you have a class named "Test" in an assembly named "ExistingAssembly.dll" and you wish to turn the class "Test" into an abstract class.
All you now need to do is:
void Main(){
//This is the existing assembly containing the type that you wish to modify
var assemblyFile = @"C:\temp\ExistingAssembly.dll";
var ass = Mono.Cecil.AssemblyDefinition.ReadAssembly(assemblyFile);
var type = ass.MainModule.GetTypes().First(t => t.Name == "Test");
//Make the type an Abstract type (class)
type.IsAbstract = true;
//Finally save the modified assembly into a new file
ass.Write(@"C:\temp\ModifiedAssembly.dll");
//The type "Test" in the above "ModifiedAssembly.dll" is now an abstract class.
}
// This is the Type that you wish to turn into an Abstract Class
public class Test {
public string DummyMethod(){
return "Dummy Return";
}
}
You can get the Mono.Cecil assembly from here (Nuget):
https://www.nuget.org/packages/Mono.Cecil/
| |
doc_23535957
|
#setcap cap_net_raw=ep /bin/ping
What is the meaning of ep and why is it required here ?
A: This sets the CAP_NET_RAW bit in both the "effective" (e) and "permitted" (p) capability sets. These two sets, along with the "inheritable" set, govern the capabilities that a process has or can set.
See more here:
capabilities - Linux man page
Capability Sets
Each thread has three capability sets containing zero or more of the
above capabilities:
Effective - the capabilities used by the kernel to
perform permission checks for the thread.
Permitted - the capabilities
that the thread may assume (i.e., a limiting superset for the
effective and inheritable sets). If a thread drops a capability from
its permitted set, it can never re-acquire that capability (unless it
exec()s a set-user-ID-root program).
inheritable - the capabilities
preserved across an execve(2). A child created via fork(2) inherits
copies of its parent's capability sets. See below for a discussion of
the treatment of capabilities during exec(). Using capset(2), a thread
may manipulate its own capability sets, or, if it has the CAP_SETPCAP
capability, those of a thread in another process.
| |
doc_23535958
|
My search page looks like:
= simple_form_for search_query, :url => :search, do |f|
= f.input :first_name
= f.input :last_name
...
Table To Display Results is here
In my controller, I have this:
def search
search_params = params[:search_query]
@people = Result of some searching
end
The above code works, except that the user can't see what values they just typed in to the form and get only the results. The form renders again, and is now blank.
My attempt at the solution is:
def search
search_params = params[:search_query]
@people = Result of some searching
@search_query = params[:search_query]
end
However, now the form throws a NoMethodError with undefined method 'first_name' for #<ActionController::Parameters:0x007fa5688aa268> at the line = f.input :first_name How can I pass my search_query back to the form?
A: I think the trick here is to use a GET instead of a POST, that way those search parameters will remain visible in your view.
Here's an example straight out of a working app I wrote...
def index
authorize! :index, Employee
params[:filter] ||= 'All' # Default to All Employees
params[:search] ||= '' # Default to blank
page_title ||= params[:filter].titleize
# Clear the search field if a filter option was selected
if session[:employee_filter] != params[:filter]
session[:employee_filter] = params[:filter]
params[:search] = ''
end
# Generate an array of our filter elements (include all departments)
@page_links = %w[All Featured Admins]
Department.all.each do |department|
@page_links << [department.title, department.name]
end
# Check and execute the filter option (defaults to All above)
case params[:filter]
when 'All'
@employees = Employee.search(params[:search]).by_name.page(params[:page]).per(15)
when 'Featured'
# We need this to be all on one page so that we can drag-and-drop position employees
@employees = Employee.search(params[:search]).is_featured.page(params[:page]).per(99999)
when 'Admins'
@employees = Employee.search(params[:search]).admins.by_name.page(params[:page]).per(15)
@page_title = 'Site Administrators'
else
@employees = Employee.search(params[:search]).dept(params[:filter]).by_index.page(params[:page]).per(15)
end
@page_title ||= "#{page_title} Employees"
@page_title = "'#{params[:search]}' in #{page_title}" unless params[:search].blank?
end
And here's the search method in the Employee model:
def self.search(search)
if search
results = where('last_name ILIKE ? OR first_name ILIKE ? OR email ILIKE ?', "%#{search}%", "%#{search}%", "%#{search}%")
results = where('title ILIKE ?', "%#{search}%") if results.blank?
results = joins(:location).where('locations.name ILIKE ?', "%#{search}%") if results.blank?
return results
end
end
And, finally, the search form from the index (in HAML format):
.sort-index
= form_tag admin_employees_path, method: 'get' do
= select_tag :filter, options_for_select(@page_links, params[:filter]), onchange: "this.form.submit();"
%br
= text_field_tag :search, params[:search], placeholder: 'Search Name, Title, or Location', size: 35
= submit_tag :search, name: nil, hidden: true
It's got some extra search stuff in there (such as additional filters), so let me know of that complicates it too much for you.
| |
doc_23535959
|
In order to do this, I create a matrix of all the jaro-winkler scores and then find the maximum values for each point in the maxtrix. However, the problem is that sometimes the string from l2 might be the best match for more than one string from l1 and I want to prevent this.
Is there some way to optimize the argmax method such that the maximum index position can only appear in the resulting matrix once?
For the sake of an example, tow lists and the subsequent code are below:
l1 = ['skinnycorebrokenblack184567', 'promtex2365h6', 'lovelinen940770', 'promtex2365h1', 'lovetrs844705',
'lovetrs844704', 'bennttrs49655', 'stella55900', 'kaxsprassel55250', 'smurfbs185573', 'kaxsprassel55880',
'victoriacort182062', 'juliatreggings916531', 'juliatreggings916530', 'milo63624505', 'promtex2365s2',
'promtex2365s1', 'promtex2365s6', 'promtex2365s4', 'stantwill160810', 'topazchini51081', 'topazchini51087',
'juliatreggings187109', 'hansentrs50924', '2454s1ladiesjeanscolure', 'promtex2365h2']
l2 = ['stannewtwill160810', 'stellatrs55900', 'jennyhigh352300', 'victoriacort180565',
'mistylowribsatins818820202031', 'lovelinen940771', 'kaxsprasseltrs55250', 'milo63626624', 'lovetrs844702',
'sarabootcuts842887019398270', 'sarabootcuts84288701939', 'victoriacords81805848817',
'ladiesjeanscolouredxxl2454s340999', 'julliatregging1871168817', 'logandrawstringpants92686705656',
'72480', 'victoriacords85203408817', 'julliatregging9673907817', 'lilypoplin9418412031', 'stellatrs56023',
'tysontrs50626', 'bolttrousers51370', 'bellamystripe184539', 'tenrhino63602214', 'kidsthermotrousers2365h1',
'bennytrouser53648', 'bluerinse070201072', 'topazchino51077', 'slimclassicblack674220203128999',
'milo63603812', 'milo63603813', 'milo63603814', 'slimclassicblack6742202031', 'lilypoplin9418402031',
'julliatregging9673917817', 'smurfjr185606', 'sarabootcuts81884571939', 'julliatregging9165318817']
#create the matrix
mat = np.matrix([[jf.jaro_distance(str(st1), str(st2))
if jf.jaro_distance(str(st1), str(st2)) > 0.85 else 0
for st2 in l2] for st1 in l1])
#get max values
mat_max = (mat.argmax(1))
#create match dictionary
match_dict = {}
for x in xrange(len(mat_max)):
if int(mat_max[x]):
match_dict[styles[x]] = s2[int(mat_max[x])]
In the above example notice that 'topazchino51077' from l2 is matched twice against strings from l1. This is exactly what I hope to prevent. The string from l2 should be matched against the best match.
A: You can model your problem in terms of the classical stable marriage problem. In your problem, pair-wise matching preferences are given by the jaro_distance of two strings; and we want to match every string in l1 to the closest string in l2 unless that string is already paired with another from l1 with more similarity.
The core of the algorithm is provided here. And this is a possible implementation:
xs = np.array([[jf.jaro_distance(x, y) for y in l2] for x in l1])
order = np.argsort(xs, axis=1)
FREE = -1 # special value to indicate no match yet
match = FREE * np.ones(len(l1), dtype=np.int_)
jnext = len(l2) * np.ones(len(l1), dtype=np.int_)
# reverse match: if string in l2 is matched to a string in l1
rev_match = FREE * np.ones(len(l2), dtype=np.int_)
while(np.any(match == FREE)): # while there is an un-matched string
i = np.where(match == FREE)[0][0] # take the first un-matched index
jnext[i] -= 1
j = order[i, jnext[i]] # next l2 string that l1[i] will be matched against
if rev_match[j] == FREE: # l2[j] is free, pair i & j together
rev_match[j], match[i] = i, j
print('{:30} --> {}'.format(l1[i], l2[j]))
else: # l2[j] is already paired
l = rev_match[j] # current l1 string that l2[j] is paired with
if xs[l, j] < xs[i, j]: # l2[j] is more similar to l1[i] than l1[l]
match[l] = FREE # unpair l & j, and pair i & j
rev_match[j], match[i] = i, j
print('{:30} -/- {}'.format(l1[l], l2[j]))
print('{:30} --> {}'.format(l1[i], l2[j]))
To see the final matching:
for i, w in enumerate(l1):
print('{:30} {}'.format(w, l2[match[i]]))
As you see, in this solution 'topazchino51077' is only paired with 'topazchini51087', because those two are more similar:
>>> jf.jaro_distance('topazchini51087', 'topazchino51077')
0.9111
>>> jf.jaro_distance('topazchini51081', 'topazchino51077')
0.8667
| |
doc_23535960
|
var csv = "Col-1,Col-2" + Environment.NewLine +
"Val1,Val2" + Environment.NewLine +
"Val3,Val3" + Environment.NewLine;
public class Line
{
public string Col1 { get; set; }
public string Col2 { get; set; }
}
ServiceStack.Text.CsvConfig<Line>.CustomHeadersMap = new Dictionary<string, string> {
{"Col1", "Col-1"},
{"Col2", "Col-2"}
};
var r2 = ServiceStack.Text.CsvSerializer.DeserializeFromString<List<Line>>(csv);
Assert.That(r2.Count() == 2, "It should be 2 rows");
Assert.That(r2[0].Col1 == "Val1", "Expected Val1");
Assert.That(r2[0].Col2 == "Val2", "Expected Val2");
CustomHeadersMap is working when SerializeToString is used. But I can't get it working when using DeserializeFromString.
A: The sample text you're trying to deserialize has very little in common with the Comma-Separated Values (CSV) format that ServiceStack's CSV Format should be used to deserialize.
I'm not aware of any .NET library that can deserialize the text format in your Sample so I'd recommend running it through some a custom regex/normalizer which can convert it to a proper .csv file and deserialize that instead. Here's an example in JavaScript:
var txt = `---------------
| Col-1 | Col-2 |
---------------
| Val1 | Val2 |
---------------
| Val3 | Val4 |
---------------
`;
var csv = txt
.replace(/^-*/mg, '')
.replace(/(^\| | \|$)/mg, '')
.replace(/ \| /mg,',')
.split(/\r?\n/g)
.filter(s => s)
.join('\r\n')
Where csv now contains the string:
Col-1,Col-2
Val1,Val2
Val3,Val4
| |
doc_23535961
|
model = ovrtrainBot(trainLabel, trainData, bestParam);
[predict_label, accuracy, decis_values] = ovrpredictBot(testLabel, testData, model);
There are strange values in "accuracy":
accuracy=[92.56 93.39 97.521 92.562 91.74 92.562 93.39 93.39 93.39
0.074 0.07 0.025 0.074 0.083 0.074 0.07 0.066 0.066
0.73 0.13 0.65 NaN 0.0007 NaN 0.104 0.433 0.104]
| |
doc_23535962
|
org_query = {"query": {"bool": {"must": [],"must_not": []}}}
I want to update another dict inside the nested dict. Here's the dict i want to add:
query_form = { "match_phrase": { "name": "steve" }}
Required Output:
org_query = {"query": {"bool": {"must": [{ "match_phrase": { "name": "steve" }],"must_not": []}}}
I found this Update value of a nested dictionary of varying depth
but it updates the value. In my case, i want to update the entire dict to the list in the key of the nested dict. How to make it possible.
A: In your case, that would be:
org_query["query"]["bool"]["must"].append(query_form)
More here: https://www.w3schools.com/python/python_dictionaries.asp
| |
doc_23535963
|
Why? Because I want to learn, I want to find new challenges. At work, things start to be boring, really. I was used to constantly encountering new things, new ideas and features. This is most of the time not the case of legacy company code, as you can imagine. And still, looking at some questions and answers here that delve into the depths of templates, shared pointers and all that stuff I happen to find myself lost, not knowing the answer or even worse - not even understanding what's going on.
That's why I'm looking for something I could code myself, using preferably only C++ (+ boost perhaps) - a command line utility, no graphics please. And I really do not want to join any open source community. Looking at others' code is helpful, I know. But that's what I do at work a lot so... no thanks. The project can be anything, meaningful or meaningless, a useful utility or just something made up that has no real usage. The only requirement is, that it would force me to really test my C++ skills. Or at least it should be very difficult or even impossible to code with basic knowledge of C++ - I'm the kind of person who is never satisfied with code that just works, so I believe this will force me to learn. But bear in mind that I'm a working man and my time is limited, so answers like "code your own OS" really won't help much.
A:
What should i code to get into the depths of advanced C++?
*
*Learn more,
*learn yet more,
*learn even more.
And, no, I'm not joking. Not at all. I started to learn C++ about 15 years ago and I'm still learning new stuff on a regular base.
Have a look at The Definitive C++ Book Guide and List and make your pick.
I'd recommend Modern C++ Design by Andrei Alexandrescu and C++ Templates The Complete Guide by Vandevoorde & Josuttis. These two alone are enough mind-blowing input to keep one programmer getting new ideas for months, if not years. (Note that reading them in this order has the advantage that Andrei's book is thinner and makes you want to read the other one just to fully grok what he writes. Reading them in reverse order has the advantage that you won't get lost as often in Andrei's book. Whatever you prefer.)
A: You mentioned creating something like 'a useless utility'. Rather, I would suggest thinking of an application or utility that would be personally of use to you, or perhaps a replacement for an application that you already use that you could design to suit your own requirements, workflows, aesthetics, etc. Pick some particular thing that you want to learn from this project, eg smart pointers, boost, template metaprogramming, regular expressions, multi-threading, networking. Then work out how to implement the application using the selected technology. Wherever there's a bit of coding to do that you know how to do already then stop, and force yourself to think of how to do it in the new idiom. For instance, try writing the application using only smart pointers.
The danger, I find, in creating a silly little demo app is that you don't have any incentive to finish it. Far better to have a goal in mind of a tool that is useful to you. This is exactly what I'm doing myself at the moment: I have a very convoluted workflow for importing photos, tagging them, renaming and editing, so I've set out to write an application in C# and WPF to do this for me. That gives me an impetus to see the project through.
Forcing yourself to solve familiar problems using unfamiliar techniques is a great learning tool.
A: Something like a matrix math library might be along the lines of what you're looking for. Plenty of potential uses of algorithms and containers. It's all been done before mind, but if you're looking for something quick and dirty to try your hand at, that's what I'd go for.
A: Write a forking or multithreaded webserver. Write lisp. Create a database (the whole implmentation, SQL optional).
A: I did all the exercises in Stroustrup's The C++ Programming Language: Special Edition over the course of about 6 months. It was worth it.
A: Try to write fancy memory pool. Surely your hands will get dirty pretty soon. If that would be not enough add garbage collection capabilities ;)
A:
The project can be anything,
meaningful or meaningless, a useful
utility or just something made up that
has no real usage.
It's much better to make something useful. You get to use it (and it will make you happier to a degree to use your own application) and you get to share it (open source project - or not).
The only requirement is, that it would
force me to really test my C++ skills.
OK, here are some ideas out of the top of my head:
Write a parser for something (expressions, a simple language, XML, logical expressions?). Better yet, write a parser/interpreter for a prolog-like language (you define predicates, objects, and relationships) then make the application perform inference on the given rules to come to a result).
Write a regular expressions package or a regular expression debugger (something where you give a string and a pattern and it tells you up to what point in the pattern the string is matched). When writing a complex regular expression, such an application would be very useful.
Write an XML package for inclusion in boost (hey, you wanted something that would force you to really test your skills).
Write a fuzzy-logic value module with fully supported logical operations (with - let's say - five truth values: false, probably false, unknown, probably true, true).
Write an AI package, allowing you to easily design and implement various neural networks with custom learning/feedback functions.
Or at least it should be very
difficult or even impossible to code
with basic knowledge of C++
With basic knowledge of C only you can write graphical platforms, operating systems and database management systems, mathematical and cryptography packages and so on (practically anything). There is nothing impossible to code with basic knowledge of C++).
Your imagination really is your limit.
A: Pick any advanced data structure (i.e. tree, priority queue etc.) and implement it.
This way you'll learn how to:
- Design in an OOP fashion
- Provide a useful and consistent API
- Correctly use inheritance, templates, inline functions to fullfill your implementation goals
- Write cross-platform code
- Write comprehensive unit-tests
Use the STL code as a reference to how things should be done.
A:
What should i code to get into the depths of advanced C++?
C++ haven't any real advanced characteristic, the language is well done, the advance characteristics are the use of lot of libraries that exists around the world.
from Math libs, graphics, communications, windows/x-windows/kde/gnome, etc.
if you wish learn a mature communication library I suggest the use of
The ADAPTIVE Communication Environment (ACE(TM)) that is a little old-fashion but have a really nice bunch of language's advanced concepts.
Have a high learning curve but is use for all mayor companies around the world.
In other hand the avoidance of use a graphic utility is masochist because you loose time in things that any GUI has solve.
You could use Netbeans or Eclipse as multi-platform, KDE Developer for linux (with KDE), MS Visual Studio in Windows, etc.
A: A C++ profiler tool would make you look at the depths of the language.
A: A fairly objective answer: I always thought that the most powerful thing about OO development was polymorphism. And the uses of it are best observed when dealing with Design Patterns.
So, I recommend getting the Design Pattern bible by GoF and writing code that uses it. The application? Can be any, as stated before, because nothing forces you to use any advanced features of anything whatsoever.
(want proof? some of the most complex systems in the world are written in COBOL by people with zero theoretical knowledge in CS)
| |
doc_23535964
|
Say I have a <Header /> stateless functional component that has the sole job of rendering two container components which are connected to a redux store.
I was thinking about promoting the <Header /> component to a container, connecting it to redux and passing down props to the subcomponents.
Would that make more sense both in terms of performance and common sense ? Having just one component connected to the store, instead of the two subcomponents.
A: That is actually a perfectly valid way of doing that. The (react-)redux documentation even says that using connect() should't be used on every single component. It is definetly okay to pass down props one or two components!
| |
doc_23535965
|
This is my SubjectTbl
+------------+--------------+---------------------+--------------+--------+----------+
| Subject_Id | Subject_Code | Subject_Name | Periods_Week | Dep_Id | Semester |
+------------+--------------+---------------------+--------------+--------+----------+
| 1 | 6012 | Basic Electronics | 10 | 1 | 1 |
| 2 | 5412 | Computer Science | 7 | 1 | 3 |
| 3 | 1421 | Musical Science | 4 | 1 | 5 |
| 4 | 547 | Network Programming | 7 | 1 | 5 |
+------------+--------------+---------------------+--------------+--------+----------+
and SubjectAllotTbl
+------------+------------+
| Subject_Id | Teacher_Id |
+------------+------------+
| 1 | 1 |
| 2 | 3 |
| 3 | 2 |
+------------+------------+
All i want to do is selecting Subject_Name from table SubjectTbl in which Same subject_id Should not be present in the SubjectAllotTbl
I'm using MySql
A: select subject_name
from SubjectTbl
where subject_id not in ( select distinct subject_id from SubjectAllotTbl)
You probably don't need distinct, unless subject_id is repeating in SubjectAllotTbl for different teacher_id
A: You can do that with a left join: all the rows that don't join will have null values on SubjectAllotTbl columns, and so you filter the result on that.
select subject_name
from SubjectTbl t1
left join
SubjectAllotTbl t2
on t1.subject_id = t2.subject_id
where t2.subject_id is null;
| |
doc_23535966
|
final_matrix=[[3.57 2.71 9.2 5.63]
[4.42 1.4 3.53 8.97]
[1.2 0.33 6.26 7.77]
[6.36 3.6 8.91 7.42]
[1.59 0.9 2.4 4.24]] # this changes in my code, im just giving a very simple version of it here
def lowest_values(final_matrix):
best_value=10000 #or any arbitrarily high number
for i in range(0,len(final_matrix[:,0])):
for j in range(0,len(final_matrix[0,:])):
if final_matrix[i,j]<best_value:
best_value=final_matrix[i,j]
lowest_val_i=i
lowest_val_j=j
return(lowest_val_i, lowest_val_j)
this returns me (1,2), which just by visual analysis is correct. i want to now find the lowest 3 values - hopefully, to build into this loop. But i really cannot think how! Or at least i dont know how to implement it. I was thinking of some if-else loop, that if the lowest value is already found, then 'void' this one and found 2nd lowest, and then same thing to find the third. But im not sure.
Please dont be too quick to shut this question down - im very new to programming, and very stuck!
A: The human Approach
I think my approach to this is different enough from different answers to share.
I am only doing 3 comparisons for every list element so it should be O(n). Also I'm not creating a entirely new list with (value, indices) tuple of all the elements.
matrix=[[3.57, 2.71, 9.2, 5.63],
[4.42, 1.4, 3.53, 8.97],
[1.2, 0.33, 6.26, 7.77],
[6.36, 3.6, 8.91, 7.42],
[1.59, 0.9, 2.4, 4.24]]
def compare_least_values(value, i, j):
global least
if value < least[2][0] :
if value < least[1][0] :
if value < least[0][0] :
least.insert(0, (value,(i,j)))
else:
least.insert(1, (value,(i,j)))
else:
least.insert(2, (value,(i,j)))
def lowest_three_values(matrix):
global least
least = [(10000, (None, None)), (10000, (None, None)), (10000, (None, None))]
for i, row in enumerate(matrix):
for j, value in enumerate(row):
compare_least_values(value, i, j)
return least[:3]
print(lowest_three_values(matrix))
Output:
[(0.33, (2, 1)), (0.9, (4, 1)), (1.2, (2, 0))]
The practical approach (Numpy)
If you're familiar with numpy than this is the way to go. Even if you're not it can be use as a copy-paste snippet.
import numpy as np
matrix=[[3.57, 2.71, 9.2, 5.63],
[4.42, 1.4, 3.53, 8.97],
[1.2, 0.33, 6.26, 7.77],
[6.36, 3.6, 8.91, 7.42],
[1.59, 0.9, 2.4, 4.24]]
matrix = np.array(matrix)
indices_1d = np.argpartition(matrix, 3, axis=None)[:3]
indices_2d = np.unravel_index(indices_1d, matrix.shape)
least_three = matrix[indices_2d]
print('least three values : ', least_three)
print('indices : ', *zip(*indices_2d) )
Output:
least three values : [0.33 0.9 1.2 ]
indices : (2, 1) (4, 1) (2, 0)
See this Stackoverflow query for detailed answer on this.
A: I didn't understand that return thing (1,2). Lowest value of matrix is 0.33. and that's position is (2,1).
So my solution for your code;
all_items = []
# i appended matrix's all items to one list
for row in final_matrix:
for i in row:
all_items.append(i)
# and i sorted that list as from min to max
all_items.sort()
# then i took first 3 values
lowest_3 = all_items[0:3]
positions = []
# and i append their positions that's in the matrix into positions
for i in lowest_3:
for row in range(len(final_matrix)):
if(i in final_matrix[row]):
positions.append([row, final_matrix[row].index(i)])
break
# lowest_3 = [0.33, 0.9, 1.2]
# positions = [[2, 1], [4, 1], [2, 0]]
A: this is my solution:
final_matrix=[[3.57, 2.71, 9.2, 5.63],
[4.42, 1.4, 3.53, 8.97],
[1.2, 0.33, 6.26, 7.77],
[6.36, 3.6, 8.91, 7.42],
[1.59, 0.9, 2.4, 4.24]]
min_values = []
for i in range(3):
mini = final_matrix[0][0]
for row in final_matrix:
for n in row:
if n < mini:
mini = n
n_index = row.index(n)
row_index = final_matrix.index(row)
min_values.append(mini)
del final_matrix[row_index][n_index]
print("Finals {}".format(min_values))
Let me explains you:
The first loop through how many min values you want (change it, you will see what I mean)
the second and the last one, loop through the matrix to take the minimun value
The line del final_matrix[row_index][n_index] will destroy the minimal number IN the original matrix
So if you want the keep the original matrix you have to create a new one and copy the original in => use deepcopy() from the copy module
A: You are looking for the N smallest items from a list of items (or a "matrix" in this case) and when N is small you can do better than sorting the items of your list by creating a heap queue, which takes linear time and then by popping the N smallest elements which is an O(log N) operation for each pop. The heap queue is an important data structure, which you should study.
import heapq
final_matrix=[[3.57, 2.71, 9.2, 5.63],
[4.42, 1.4, 3.53, 8.97],
[1.2, 0.33, 6.26, 7.77],
[6.36, 3.6, 8.91, 7.42],
[1.59, 0.9, 2.4, 4.24]]
def lowest_values(final_matrix):
# create a flat list, l, from the matrix
# each element is a tuple: (value, x-coordinate, y-coordinate)
l = [(final_matrix[x][y], x, y)
for x in range(len(final_matrix))
for y in range(len(final_matrix[0]))
]
heapq.heapify(l) # O(N) time
for _ in range(3):
# pop next smallest tuple:
value, x, y = heapq.heappop(l) # O(log N) time
print(f'value={value}, x={x}, y={y}')
lowest_values(final_matrix)
Prints:
value=0.33, x=2, y=1
value=0.9, x=4, y=1
value=1.2, x=2, y=0
Note
The above code could have been simplified to the following, which is probably even slightly more efficient if all you want are the 3 smallest items and then you have no further need for the heap queue structure. But I wanted to show the two basic operations of creating a heap queue from a list and then successively producing the smallest items from that heap queue:
import heapq
final_matrix=[[3.57, 2.71, 9.2, 5.63],
[4.42, 1.4, 3.53, 8.97],
[1.2, 0.33, 6.26, 7.77],
[6.36, 3.6, 8.91, 7.42],
[1.59, 0.9, 2.4, 4.24]]
def lowest_values(final_matrix):
# create a flat list, l, from the matrix
# each element is a tuple: (value, x-coordinate, y-coordinate)
l = [(final_matrix[x][y], x, y)
for x in range(len(final_matrix))
for y in range(len(final_matrix[0]))
]
for value, x, y in heapq.nsmallest(3, l):
print(f'value={value}, x={x}, y={y}')
lowest_values(final_matrix)
| |
doc_23535967
|
are accessible which are defined by the superclass
class A {
int i=10;
void adsip() {
System.out.println(i);
}
}
class B extends A {
int j=20;
void bdsip() {
System.out.println(i+j);
}
}
class inherit4 {
public static void main(String[] x) {
A a=new A();
B b=new B();
System.out.println("b.i="+b.i+"b.j="+b.j);
b.adsip();
b.bdsip();
a=b;
System.out.println("a.i="+a.i);
a.adsip();
}
}
ABOVE CODE IS WORKING FINE
but after adding a.j and a.bdisp(); error is generated,as far as i know a & b in the above code represent
refrence to memory allocation of objects of class A & B then why code is not able to access a.j and a.bdsip(); in above code.
A: ClassCastException - Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
For example, the following code generates a ClassCastException:
Object x = new Integer(0);
System.out.println((String)x);
Also please refer this thread.
Can someone explain “ClassCastException” in Java?
A:
why only those members are accessible which are defined by the superclass
Because, at runtime, the superclass reference may be pointing to a superclass instance or instance of any class in the subclass hierarchy.
superclass has method m1, but subclass has method m1 and m2. You want to access m2 using a reference of superclass. But what if, at runtime, the reference is pointing to an instance of superclass (which does not have m2) ?
So the end result is that -
At runtime, the only members that are guaranteed to be accessible using superclass reference are the ones defined in the superclass.
A: In inheritance child can access parent data but the reverse is not possible. parent can't access child data. So here object of class A , a can't access Class B's method or data.
| |
doc_23535968
|
char s[1000]="E:\\worldisnotenough.dll"; //Works
If I use GetFullPathNameA DLL injections do not work, and they do not give any runtime or compile time errors. I checked this:
char s[1000];
int ax =GetFullPathNameA("worldisnotenough.dll",
1000,
s, //Output to save the full DLL path
NULL);
std::cout<<s; //prints the correct path. Working.
The line cout << s prints the correct path, but DLL injection doesn't happen. No errors occur. I checked VirtualAllocEx, WriteProcessMemory, and CreateRemoteThread, and all of them are working properly.
Edit: complete code
#include <QCoreApplication>
#include<windows.h>
#include<tchar.h>
#include<iostream>
#include "E:/Users/Gen/qt project freiza/FreizaLibrary/freizalibrary.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// FreizaLibrary lib;
// QTextStream s(stdin);
// QString value = s.readLine();
// lib.injection(value.toInt());
int procID = 13044;
HANDLE hHandle = OpenProcess( PROCESS_CREATE_THREAD |
PROCESS_QUERY_INFORMATION |
PROCESS_VM_OPERATION |
PROCESS_VM_WRITE |
PROCESS_VM_READ,
FALSE,
procID );
QString dllName = "worldisnotenough.dll";
QFile myDllFile(dllName);
QFileInfo dllInfo(dllName);
QString str =dllInfo.absoluteFilePath();
char s[]="E:\\Users\\Gen\\qt project freiza\\build-libtester-FreizaKit-Release\\release\\worldisnotenough.dll";
std::cout<<strlen(s)<<"\n";
int ax =GetFullPathNameA("worldisnotenough.dll",
86, //I set it to 1000 before posting this question.
s, //Output to save the full DLL path
NULL);
//qDebug()<< QString::fromUtf8(s) <<" "<< ax;
std::cout<<s<<"size "<<ax;
LPVOID dllPathAddr = VirtualAllocEx(hHandle,
0,
strlen(s),
MEM_RESERVE|MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
std::cout<<" test \n";
std::cout<<(int*)dllPathAddr<<endl;
if(dllPathAddr==NULL)
{
qDebug()<<"virtual failed";
}
size_t x;
int n= WriteProcessMemory(hHandle,
dllPathAddr,
s,
strlen(s),
&x);
if(n==0)
{
qDebug()<<"write failed";
}
std::cout<<endl<<n<<"\t"<<x;
LPVOID addr = (LPVOID)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryA");
if(addr==NULL)
{
qDebug()<<"get proc failed";
}
HANDLE rThread = CreateRemoteThread(hHandle, NULL, 0, (LPTHREAD_START_ROUTINE)addr,dllPathAddr, 0, NULL);
if(rThread==NULL)
{
qDebug()<<"create remote failed";
}
WaitForSingleObject(rThread, INFINITE);
VirtualFreeEx(hHandle, dllPathAddr, 0, MEM_RELEASE);
CloseHandle(hHandle);
qDebug()<< "done";
return a.exec();
}
And why negative votes?
When I post full code. People say only post the segment of code which is not working.
And I explained the situation to its fullest. Because of these negative votes now I won't be able to ask questions on stackoverflow. Thank you.
A: you need to use
strlen(s)+1
cause it returnes the lenght of the string without including the terminating null character itself! So VirtualAllocEx and WriteProcessMemory will not write the '\0' char and the filename will terminate at a "random" position in memory.
Also
char s[]="E:\\Users\\Gen\\qt project freiza\\build-libtester-FreizaKit-Release\\release\\worldisnotenough.dll"; //- Length: 93+1
int ax =GetFullPathNameA("worldisnotenough.dll",
sizeof(s), //<-- old: 86 but s[] is 93 + 1 if this has to hold the total path may it was to small?
s, //Output to save the full DLL path
NULL);
looks wong?!
A: Your problem is you are trying to use a statically defined character array as a buffer for GetFullPathNameA!
See here:
char s[]="E:\\Users\\Gen\\qt project freiza\\build-libtester-FreizaKit-Release\\release\\worldisnotenough.dll";
std::cout<<strlen(s)<<"\n";
int ax =GetFullPathNameA("worldisnotenough.dll",
86, //1000 is no good, MAX_PATH is 260
s, //Using 's' as a buffer? Don't do that please!
NULL);
Furthermore when using the ANSI version which you are as denoted by the 'A' a maximum path length of 260 characters is the maximum. MAX_PATH==260
"In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\?\" "
Fixed code: (However I don't use QT so that is missing from here, shouldn't matter though as it wasn't used for anything needed for the injecting to work)
#include <windows.h>
#include <iostream>
#include <tlhelp32.h>
HANDLE GetProcessHandle(wchar_t *ProcessName,ULONG *ReturnedProcessId);
int main(int argc, char *argv[])
{
ULONG procID;
HANDLE hHandle=GetProcessHandle(L"ExeToInjectInto.exe",&procID);
/*HANDLE hHandle=OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION|
PROCESS_VM_WRITE|PROCESS_VM_READ,FALSE,procID);*/
std::cout<<"handle: "<<hHandle<<" process ID: "<<procID<<"\n";
char s[]="C:\\Users\\DBVM_OS\\CodeBlocksProjects\\HelpFreizaProject\\bin\\Debug\\mytestdll.dll";
std::cout<<s<<"\n"<<strlen(s)<<"\n";
//First Problem:
/*In the ANSI version of this function, the name is limited to MAX_PATH characters.
To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\"
*/
//Second Problem:
/* Don't use a defined static char[] as a buffer! allocate some memory or use the stack */
//char s2[MAX_PATH];
//int ax=GetFullPathNameA("mytestdll.dll",MAX_PATH,s2,0);
char *s2=new char[MAX_PATH];
if(s2==0) return 0;
int ax=GetFullPathNameA("mytestdll.dll",MAX_PATH,s2,0);
std::cout<<s2<<"\nsize returned: "<<ax<<" strlen: "<<strlen(s2)<<"\n";
LPVOID dllPathAddr=VirtualAllocEx(hHandle,0,(strlen(s2)+1),MEM_COMMIT,PAGE_EXECUTE_READWRITE);
std::cout<<"Remotely Allocated String Address: \n";
std::cout<<(int*)dllPathAddr<<"\n";
if(dllPathAddr==0)
{
OutputDebugStringA("VirtualAllocEx failed...");
return 0;
}
SIZE_T x;
BOOL n=WriteProcessMemory(hHandle,dllPathAddr,s2,(strlen(s2)+1),&x);
if(n==FALSE)
{
OutputDebugStringA("write failed");
VirtualFreeEx(hHandle,dllPathAddr,0,MEM_RELEASE);
CloseHandle(hHandle);
return 0;
}
std::cout<<"WriteProcessMemory Success: "<<n<<", Bytes Written: "<<x<<"\n";
LPVOID addr=(LPVOID)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryA");
if(addr==0)
{
OutputDebugStringA("get proc failed");
VirtualFreeEx(hHandle,dllPathAddr,0,MEM_RELEASE);
CloseHandle(hHandle);
return 0;
}
std::cout<<"LoadLibraryA: "<<addr<<"\n";
HANDLE rThread=CreateRemoteThread(hHandle,0,0,(LPTHREAD_START_ROUTINE)addr,dllPathAddr,0,0);
if(rThread==0)
{
OutputDebugStringA("create remote failed");
VirtualFreeEx(hHandle,dllPathAddr,0,MEM_RELEASE);
CloseHandle(hHandle);
return 0;
}
WaitForSingleObject(rThread,INFINITE);
std::cout<<"DLL Should have been injected successfully at this point...\nFreeing remote string";
BOOL freed=VirtualFreeEx(hHandle,dllPathAddr,0,MEM_RELEASE);
if(freed==0) OutputDebugStringA("Freeing Remote String Failed...");
delete[] s2; //if you dynamically allocated s2 like I've done...
CloseHandle(hHandle);
return 0;
}
HANDLE GetProcessHandle(wchar_t *ProcessName,ULONG *ReturnedProcessId)
{
PROCESSENTRY32W pe;
HANDLE Snap;
ZeroMemory(&pe, sizeof(PROCESSENTRY32W));
pe.dwSize=sizeof(PROCESSENTRY32W);
Snap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if(Snap==INVALID_HANDLE_VALUE) return 0;
BOOL bProcess=Process32FirstW(Snap,&pe);
while(bProcess)
{
if(_wcsicmp(pe.szExeFile,ProcessName)==0)
{
HANDLE ProcessHandle=OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION|
PROCESS_VM_WRITE|PROCESS_VM_READ,FALSE,pe.th32ProcessID);
if(ReturnedProcessId!=0)
*ReturnedProcessId=pe.th32ProcessID;
CloseHandle(Snap);
return ProcessHandle;
}
bProcess=Process32NextW(Snap, &pe);
}
if(ReturnedProcessId!=0) *ReturnedProcessId=0;
CloseHandle(Snap);
return 0;
}
| |
doc_23535969
|
and my jdk version is 1.8(64-bit).flex 4 ,as3
package org.red5.demos;
import org.red5.server.adapter.ApplicationAdapter;
import org.red5.server.api.IConnection;
import org.red5.server.api.scope.IScope;
import org.red5.server.api.service.IServiceCapableConnection;
import org.red5.server.api.stream.IServerStream;
/**
* @author user
*
*/
public class Application extends ApplicationAdapter {
private IScope appScope;
private IServerStream serverStream;
@Override
public boolean appStart(IScope app){
super.appStart(app);
System.out.println("hello demo start");
appScope=app;
return true;
}
@Override
public boolean appConnect(IConnection conn,Object[]obj){
IScope appScope=conn.getScope();
System.out.println("appConnect");
callient(conn); //appConnect and calling client method
return super.appConnect(conn, obj);
}
private void callient(IConnection conn){
if(conn instanceof IServiceCapableConnection){
System.out.println("connect to flash side");
((IServiceCapableConnection) conn).invoke("yourFunctionInFlash"); // involing client side method ,but print "connect to flash side"
}
}
//disconnected
@Override
public void appDisconnect(IConnection conn){
if(appScope==conn.getScope() && serverStream!=null){
serverStream.close();
}
super.appDisconnect(conn);
}
}
and my flex side code,in my demo ,,after connect to red5 server application ,the netStatus info is success.
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="windowedapplication1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.graphics.codec.JPEGEncoder;
private var cam:Camera;
private var netConnection:NetConnection;
private var netStream:NetStream;**strong text**
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
netConnection=new NetConnection();
netConnection.client = { onBWDone: function():void{} };
netConnection.addEventListener(NetStatusEvent.NET_STATUS,connectionServerHandler);
netConnection.connect("rtmp://192.168.61.132/Hello","ssl");//connect to Hello App
}
public function sayHello(reponder:String):void{
trace(reponder+"from server side ");
}
public function yourFunctionInFlash():void{
trace("hello"); //get message from server side
}
private function connectionServerHandler(event:NetStatusEvent):void{
trace(event.info.code); //it work success
}
]]>
</fx:Script>
</s:WindowedApplication>
but now ,flex side yourFunctionInFlash()method doesn't work,and server side also print "connect to flash side"message?>>> is any other I have missed?
thank you a lot .
A: Method yourFunctionInFlash should be defined in netConnection.client object. In your case you should assign netConnection.client = this. Also call super.appConnect on back end before invoking client method.
| |
doc_23535970
|
I tried:
obj = someobject
obj.a = object()
setattr(obj.a, 'somefield', 'somevalue')
but this didn't work.
Any ideas?
edit:
I am setting the attributes from a for loop which loops through a list of values, e.g.
params = ['attr1', 'attr2', 'attr3']
obj = someobject
obj.a = object()
for p in params:
obj.a.p # where p comes from for loop variable
In the above example I would get obj.a.attr1, obj.a.attr2, obj.a.attr3.
I used the setattr function because I didn't know how to do obj.a.NAME from a for loop.
How would I set the attribute based on the value of p in the example above?
For details on why it doesn't work, see Can't set attributes on instance of "object" class.
A: as docs say:
Note: object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.
You could just use dummy-class instance.
A: The mock module is basically made for that.
import mock
obj = mock.Mock()
obj.a = 5
A: You can also use a class object directly; it creates a namespace:
class a: pass
a.somefield1 = 'somevalue1'
setattr(a, 'somefield2', 'somevalue2')
A: The built-in object can be instantiated but can't have any attributes set on it. (I wish it could, for this exact purpose.) It doesn't have a __dict__ to hold the attributes.
I generally just do this:
class Object(object):
pass
a = Object()
a.somefield = somevalue
When I can, I give the Object class a more meaningful name, depending on what kind of data I'm putting in it.
Some people do a different thing, where they use a sub-class of dict that allows attribute access to get at the keys. (d.key instead of d['key'])
Edit: For the addition to your question, using setattr is fine. You just can't use setattr on object() instances.
params = ['attr1', 'attr2', 'attr3']
for p in params:
setattr(obj.a, p, value)
A: These solutions are very helpful during testing. Building on everyone else's answers I do this in Python 2.7.9 (without staticmethod I get a TypeError (unbound method...):
In [11]: auth = type('', (), {})
In [12]: auth.func = staticmethod(lambda i: i * 2)
In [13]: auth.func(2)
Out[13]: 4
A: There are a few ways to reach this goal.
Basically you need an object which is extendable.
obj.a = type('Test', (object,), {})
obj.a.b = 'fun'
obj.b = lambda:None
class Test:
pass
obj.c = Test()
A: If we can determine and aggregate all the attributes and values together before creating the nested object, then we could create a new class that takes a dictionary argument on creation.
# python 2.7
class NestedObject():
def __init__(self, initial_attrs):
for key in initial_attrs:
setattr(self, key, initial_attrs[key])
obj = someobject
attributes = { 'attr1': 'val1', 'attr2': 'val2', 'attr3': 'val3' }
obj.a = NestedObject(attributes)
>>> obj.a.attr1
'val1'
>>> obj.a.attr2
'val2'
>>> obj.a.attr3
'val3'
We can also allow keyword arguments. See this post.
class NestedObject(object):
def __init__(self, *initial_attrs, **kwargs):
for dictionary in initial_attrs:
for key in dictionary:
setattr(self, key, dictionary[key])
for key in kwargs:
setattr(self, key, kwargs[key])
obj.a = NestedObject(attr1='val1', attr2='val2', attr3= 'val3')
A: You could use my ancient Bunch recipe, but if you don't want to make a "bunch class", a very simple one already exists in Python -- all functions can have arbitrary attributes (including lambda functions). So, the following works:
obj = someobject
obj.a = lambda: None
setattr(obj.a, 'somefield', 'somevalue')
Whether the loss of clarity compared to the venerable Bunch recipe is OK, is a style decision I will of course leave up to you.
A: Now you can do (not sure if it's the same answer as evilpie):
MyObject = type('MyObject', (object,), {})
obj = MyObject()
obj.value = 42
A: Try the code below:
$ python
>>> class Container(object):
... pass
...
>>> x = Container()
>>> x.a = 10
>>> x.b = 20
>>> x.banana = 100
>>> x.a, x.b, x.banana
(10, 20, 100)
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'banana']
A: There is types.SimpleNamespace class in Python 3.3+:
obj = someobject
obj.a = SimpleNamespace()
for p in params:
setattr(obj.a, p, value)
# obj.a.attr1
collections.namedtuple, typing.NamedTuple could be used for immutable objects. PEP 557 -- Data Classes suggests a mutable alternative.
For a richer functionality, you could try attrs package. See an example usage. pydantic may be worth a look too.
A: Which objects are you using? Just tried that with a sample class and it worked fine:
class MyClass:
i = 123456
def f(self):
return "hello world"
b = MyClass()
b.c = MyClass()
setattr(b.c, 'test', 123)
b.c.test
And I got 123 as the answer.
The only situation where I see this failing is if you're trying a setattr on a builtin object.
Update: From the comment this is a repetition of: Why can't you add attributes to object in python?
A: I think the easiest way is through the collections module.
import collections
FinanceCtaCteM = collections.namedtuple('FinanceCtaCte', 'forma_pago doc_pago get_total')
def get_total(): return 98989898
financtacteobj = FinanceCtaCteM(forma_pago='CONTADO', doc_pago='EFECTIVO',
get_total=get_total)
print financtacteobj.get_total()
print financtacteobj.forma_pago
print financtacteobj.doc_pago
A: if you are looking for chain assignment, to do things such as django model template abstract attribute assigning:
from types import SimpleNamespace
def assign(target, *args, suffix):
ls = target
for i in range(len(args) - 1):
a = args[i]
ns = SimpleNamespace()
setattr(ls, a, ns)
ls = ns
setattr(ls, args[-1], suffix)
return ls
a = SimpleNamespace()
assign(a, 'a', 'b', 'c', suffix={'name': 'james'})
print(a.a.b.c)
# {'name': 'james'}
which allows you to pass model as a target, and assign end attribute to it.
A: Coming to this late in the day but here is my pennyworth with an object that just happens to hold some useful paths in an app but you can adapt it for anything where you want a sorta dict of information that you can access with getattr and dot notation (which is what I think this question is really about):
import os
def x_path(path_name):
return getattr(x_path, path_name)
x_path.root = '/home/x'
for name in ['repository', 'caches', 'projects']:
setattr(x_path, name, os.path.join(x_path.root, name))
This is cool because now:
In [1]: x_path.projects
Out[1]: '/home/x/projects'
In [2]: x_path('caches')
Out[2]: '/home/x/caches'
So this uses the function object like the above answers but uses the function to get the values (you can still use (getattr, x_path, 'repository') rather than x_path('repository') if you prefer).
A: This works just fine:
exec("obj.a."+p)
If you want to set the attribute to some value, do this:
exec("obj.a."+p+"=(the value here)")
For the value to be a string you will have to use these \" instead of quotation marks unless you have the value stored in a variable.
A: Other way i see, this way:
import maya.cmds
def getData(objets=None, attrs=None):
di = {}
for obj in objets:
name = str(obj)
di[name]=[]
for at in attrs:
di[name].append(cmds.getAttr(name+'.'+at)[0])
return di
acns=cmds.ls('L_vest_*_',type='aimConstraint')
attrs=['offset','aimVector','upVector','worldUpVector']
getData(acns,attrs)
A: di = {}
for x in range(20):
name = '_id%s' % x
di[name] = type(name, (object), {})
setattr(di[name], "attr", "value")
| |
doc_23535971
|
private void getFirstVisibleMediaRecyclerView() {
int findFirstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
int findLastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
int [] positions = { findFirstVisibleItemPosition, findLastVisibleItemPosition };
Rect scrollBounds = new Rect();
recyclerView.getDrawingRect(scrollBounds);
int[] location = new int[2];
for (int position : positions) {
RecyclerView.ViewHolder item = recyclerView.findViewHolderForAdapterPosition(0);
PostAdapter.PostViewHolder viewHolder = (PostAdapter.PostViewHolder) item;
viewHolder.mediaRecyclerView.getLocationInWindow(location);
if (location[1] < 0 || location[1] > scrollBounds.bottom) {
//
} else {
viewHolder.doSomething();
}
}
}
And my adapter class looks like this (I've removed parts that aren't important for this question):
public class PostAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public class PostViewHolder extends RecyclerView.ViewHolder {
public RecyclerView mediaRecyclerView;
public PostViewHolder(View v) {
super(v);
mediaRecyclerView = v.findViewById(R.id.media_recycler_view);
}
public void doSomething() {
LinearLayoutManager layoutManager = (LinearLayoutManager) mediaRecyclerView.getLayoutManager();
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// LAYOUT MANAGER IS NULL HERE AND I DON'T KNOW WHY
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (layoutManager == null) {
return;
}
//
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
holder.mediaRecyclerView.setLayoutManager(layoutManager);
PostMediaAdapter mAdapter = new PostMediaAdapter(context, getData());
holder.mediaRecyclerView.setAdapter(mAdapter);
}
}
However, the layoutManager in the doSomething() method of the view holder is returning null, and I have no idea why.
Please help!
A: First of all don't add layoutManager into onBindViewHolder you should add once your activity/fragment created.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.id);
binding.rvList.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false))
}
because it effect performance of your application. try this remove form onBindViewHolder, what you want in doSomething() so I can suggest you need layoutManager object in adapter or its garbage.
| |
doc_23535972
|
(Would like to make it automatic close a previous row when click another row, Right now it can expandable all row at a time)
And this is the code https://jsfiddle.net/4L4e88w6/11/
//uses classList, setAttribute, and querySelectorAll
//if you want this to work in IE8/9 youll need to polyfill these
(function() {
var d = document,
accordionToggles = d.querySelectorAll('.js-accordionTrigger'),
setAria,
setAccordionAria,
switchAccordion,
touchSupported = ('ontouchstart' in window),
pointerSupported = ('pointerdown' in window);
skipClickDelay = function(e) {
e.preventDefault();
e.target.click();
}
setAriaAttr = function(el, ariaType, newProperty) {
el.setAttribute(ariaType, newProperty);
};
setAccordionAria = function(el1, el2, expanded) {
switch (expanded) {
case "true":
setAriaAttr(el1, 'aria-expanded', 'true');
setAriaAttr(el2, 'aria-hidden', 'false');
break;
case "false":
setAriaAttr(el1, 'aria-expanded', 'false');
setAriaAttr(el2, 'aria-hidden', 'true');
break;
default:
break;
}
};
//function
switchAccordion = function(e) {
console.log("triggered");
e.preventDefault();
var thisAnswer = e.target.parentNode.nextElementSibling;
var thisQuestion = e.target;
if (thisAnswer.classList.contains('is-collapsed')) {
setAccordionAria(thisQuestion, thisAnswer, 'true');
} else {
setAccordionAria(thisQuestion, thisAnswer, 'false');
}
thisQuestion.classList.toggle('is-collapsed');
thisQuestion.classList.toggle('is-expanded');
thisAnswer.classList.toggle('is-collapsed');
thisAnswer.classList.toggle('is-expanded');
thisAnswer.classList.toggle('animateIn');
};
for (var i = 0, len = accordionToggles.length; i < len; i++) {
if (touchSupported) {
accordionToggles[i].addEventListener('touchstart', skipClickDelay, false);
}
if (pointerSupported) {
accordionToggles[i].addEventListener('pointerdown', skipClickDelay, false);
}
accordionToggles[i].addEventListener('click', switchAccordion, false);
}
})();
* {
box-sizing: border-box;
}
.heading-primary {
padding: 3em 0em 0.5em 0em;
text-align: left;
}
.accordion dl,
.accordion-list {
border: 1px solid #ddd;
}
.accordion dl:after,
.accordion-list:after {
content: "";
display: block;
height: 0.5em;
width: 100%;
background-color: #5c5c5c;
}
.accordion dd,
.accordion__panel {
background-color: #E3F2FD;
font-size: 1em;
line-height: 1.5em;
}
.accordion p {
padding: 1em 2em 1em 2em;
}
.accordion {
position: relative;
background-color: #eee;
}
.accordionTitle,
.accordion__Heading {
text-align: left;
font-weight: 500;
padding: 1em;
display: block;
text-decoration: none;
color: #424242;
/* -webkit-transition: background-color 0.2s ease-in-out;
transition: background-color 0.2s ease-in-out; */
border-bottom: 1px solid #2a54a2;
}
.accordionTitle:before,
.accordion__Heading:before {
content: "?";
font-size: 1.5em;
font-weight: bold;
line-height: 0.5em;
float: right;
-webkit-transition: -webkit-transform 0.3s ease-in-out;
transition: -webkit-transform 0.3s ease-in-out;
transition: transform 0.3s ease-in-out;
transition: transform 0.3s ease-in-out, -webkit-transform 0.3s ease-in-out;
}
.accordionTitle:hover,
.accordion__Heading:hover {
background-color: #01579B;
color: white;
}
.accordionTitleActive,
.accordionTitle.is-expanded {
background-color: #01579B;
color: white;
}
.accordionTitleActive:before,
.accordionTitle.is-expanded:before {
content: "+";
-webkit-transform: rotate(-225deg);
-ms-transform: rotate(-225deg);
transform: rotate(-225deg);
font-size: 2.5em;
font-weight: 100;
}
.accordionItem {
height: auto;
overflow: hidden;
max-height: 50em;
-webkit-transition: max-height 1s;
transition: max-height 1s;
}
@media screen and (min-width: 48em) {
.accordionItem {
/*max-height: 15em;*/
-webkit-transition: max-height 0.25s;
transition: max-height 0.25s;
}
}
.accordionItem.is-collapsed {
max-height: 0;
}
.no-js .accordionItem.is-collapsed {
max-height: auto;
}
.animateIn {
-webkit-animation: accordionIn 0.45s normal ease-in-out both 1;
animation: accordionIn 0.45s normal ease-in-out both 1;
}
.animateOut {
-webkit-animation: accordionOut 0.45s alternate ease-in-out both 1;
animation: accordionOut 0.45s alternate ease-in-out both 1;
}
@-webkit-keyframes accordionIn {
0% {
opacity: 0;
-webkit-transform: translateY(38px);
transform: translateY(38px);
}
100% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
}
@keyframes accordionIn {
0% {
opacity: 0;
-webkit-transform: translateY(38px);
transform: translateY(38px);
-webkit-transform-origin: 50% 0;
transform-origin: 50% 0;
/*
-webkit-transform: scale(0.9) rotateX(-60deg);
transform: scale(0.9) rotateX(-60deg);
-webkit-transform-origin: 50% 0;
transform-origin: 50% 0; */
}
100% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
}
@-webkit-keyframes accordionOut {
0% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
100% {
opacity: 0;
-webkit-transform: scale(0.9) rotateX(-60deg);
transform: scale(0.9) rotateX(-60deg);
}
}
@keyframes accordionOut {
0% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
100% {
opacity: 0;
-webkit-transform: scale(0.9) rotateX(-60deg);
transform: scale(0.9) rotateX(-60deg);
}
}
<div class="container">
<h3 class="heading-primary">Q&A</h3>
<div class="accordion">
<dl>
<dt>
<a href="#accordion1" aria-expanded="false" aria-controls="accordion1" class="accordion-title accordionTitle js-accordionTrigger">First Accordion heading</a>
</dt>
<dd class="accordion-content accordionItem is-collapsed" id="accordion1" aria-hidden="true">
<p>Lorem ipsum dolor sit amet, consectetur <a href="http://www.google.com">Test</a>adipiscing elit. Morbi eu interdum diam. Donec interdum porttitor risus non bibendum. Maecejusto dui, sodales quis luctus a, iaculis eget mauris. </p>
<p>Aliquam dapibus, ante quis fringilla feugiat, mauris risus condimentum massa, at elementum r. Quisque blandit adipiscing erat vitae dapibus. Nulla aliquam magna nec elementum tincidunt.</p>
<p>Aliquam dapibus, ante quis fringilla </p>
</dd>
<dt>
<a href="#accordion1" aria-expanded="false" aria-controls="accordion1" class="accordion-title accordionTitle js-accordionTrigger">Second Accordion heading</a>
</dt>
<dd class="accordion-content accordionItem is-collapsed" id="accordion1" aria-hidden="true">
<p>Lorem ipsum dolor sit amet, consectetur <a href="http://www.google.com">Test</a>adipiscing elit. Morbi eu interdum diam. Donec interdum porttitor risus non bibendum. Maecenas sollicitudin eros in quam imperdiet placerat. Cras justo purus, rhoncus
nec lobortis ut, iaculis vel ipsum. Donec dignissim arcu nec elit faucibus condimentum. Donec facilisis consectetur enim sit amet varius. Pellentesque justo dui, sodales quis luctus a, iaculis eget mauris. </p>
<p>Aliquam dapibus, ante quis fringilla feugiat, mauris risus condimentum massa, at elementum libero quam ac ligula. Pellentesque at rhoncus dolor. Duis porttitor nibh ut lobortis aliquam. Nullam eu dolor venenatis mauris placerat tristique eget
id dolor. Quisque blandit adipiscing erat vitae dapibus. Nulla aliquam magna nec elementum tincidunt.</p>
</dd>
<dt>
<a href="#accordion1" aria-expanded="false" aria-controls="accordion1" class="accordion-title accordionTitle js-accordionTrigger">Third Accordion heading</a>
</dt>
<dd class="accordion-content accordionItem is-collapsed" id="accordion1" aria-hidden="true">
<p>Lorem ipsum dolor sit amet, consectetur <a href="http://www.google.com">Test</a>adipiscing elit. Morbi eu interdum diam. Donec interdum porttitor risus non bibendum. Maecenas sollicitudin eros in quam imperdiet placerat. Cras justo purus, rhoncus
nec lobortis ut, iaculis vel ipsum. Donec dignissim arcu nec elit faucibus condimentum. Donec facilisis consectetur enim sit amet varius. Pellentesque justo dui, sodales quis luctus a, iaculis eget mauris. </p>
<p>Aliquam dapibus, ante quis fringilla feugiat, mauris risus condimentum massa, at elementum libero quam ac ligula. Pellentesque at rhoncus dolor. Duis porttitor nibh ut lobortis aliquam. Nullam eu dolor venenatis mauris placerat tristique eget
id dolor. Quisque blandit adipiscing erat vitae dapibus. Nulla aliquam magna nec elementum tincidunt.</p>
</dd>
</dl>
</div>
</div>
A: I agree with @DanielBeck that your code can be simplified further and the typical approach is to collapse all the items and then expand the currently clicked item.
However here is another approach:
You can keep a reference to expanded element and collapse it before expanding a new one. Like this:
//uses classList, setAttribute, and querySelectorAll
//if you want this to work in IE8/9 youll need to polyfill these
(function() {
var d = document,
accordionToggles = d.querySelectorAll('.js-accordionTrigger'),
setAria,
setAccordionAria,
switchAccordion,
touchSupported = ('ontouchstart' in window),
pointerSupported = ('pointerdown' in window);
skipClickDelay = function(e) {
e.preventDefault();
e.target.click();
}
setAriaAttr = function(el, ariaType, newProperty) {
el.setAttribute(ariaType, newProperty);
};
setAccordionAria = function(el1, el2, expanded) {
switch (expanded) {
case "true":
setAriaAttr(el1, 'aria-expanded', 'true');
setAriaAttr(el2, 'aria-hidden', 'false');
break;
case "false":
setAriaAttr(el1, 'aria-expanded', 'false');
setAriaAttr(el2, 'aria-hidden', 'true');
break;
default:
break;
}
};
//function
var expanded;
switchAccordion = function(e) {
console.log("triggered");
e.preventDefault();
var thisAnswer = e.target.parentNode.nextElementSibling;
var thisQuestion = e.target;
if(expanded) {
setAccordionAria(expanded, thisAnswer, 'false');
expanded.classList.toggle('is-collapsed');
expanded.classList.toggle('is-expanded');
var expandedAns = expanded.parentNode.nextElementSibling;
expandedAns.classList.toggle('is-collapsed');
expandedAns.classList.toggle('is-expanded');
expandedAns.classList.toggle('animateIn');
if(expanded == thisQuestion){
expanded = undefined;
return;
}
}
if(thisAnswer.classList.contains('is-collapsed')) {
setAccordionAria(thisQuestion, thisAnswer, 'true');
expanded = thisQuestion;
} else {
setAccordionAria(thisQuestion, thisAnswer, 'false');
}
thisQuestion.classList.toggle('is-collapsed');
thisQuestion.classList.toggle('is-expanded');
thisAnswer.classList.toggle('is-collapsed');
thisAnswer.classList.toggle('is-expanded');
thisAnswer.classList.toggle('animateIn');
};
for (var i = 0, len = accordionToggles.length; i < len; i++) {
if (touchSupported) {
accordionToggles[i].addEventListener('touchstart', skipClickDelay, false);
}
if (pointerSupported) {
accordionToggles[i].addEventListener('pointerdown', skipClickDelay, false);
}
accordionToggles[i].addEventListener('click', switchAccordion, false);
}
})();
* {
box-sizing: border-box;
}
.heading-primary {
padding: 3em 0em 0.5em 0em;
text-align: left;
}
.accordion dl,
.accordion-list {
border: 1px solid #ddd;
}
.accordion dl:after,
.accordion-list:after {
content: "";
display: block;
height: 0.5em;
width: 100%;
background-color: #5c5c5c;
}
.accordion dd,
.accordion__panel {
background-color: #E3F2FD;
font-size: 1em;
line-height: 1.5em;
}
.accordion p {
padding: 1em 2em 1em 2em;
}
.accordion {
position: relative;
background-color: #eee;
}
.accordionTitle,
.accordion__Heading {
text-align: left;
font-weight: 500;
padding: 1em;
display: block;
text-decoration: none;
color: #424242;
/* -webkit-transition: background-color 0.2s ease-in-out;
transition: background-color 0.2s ease-in-out; */
border-bottom: 1px solid #2a54a2;
}
.accordionTitle:before,
.accordion__Heading:before {
content: "?";
font-size: 1.5em;
font-weight: bold;
line-height: 0.5em;
float: right;
-webkit-transition: -webkit-transform 0.3s ease-in-out;
transition: -webkit-transform 0.3s ease-in-out;
transition: transform 0.3s ease-in-out;
transition: transform 0.3s ease-in-out, -webkit-transform 0.3s ease-in-out;
}
.accordionTitle:hover,
.accordion__Heading:hover {
background-color: #01579B;
color: white;
}
.accordionTitleActive,
.accordionTitle.is-expanded {
background-color: #01579B;
color: white;
}
.accordionTitleActive:before,
.accordionTitle.is-expanded:before {
content: "+";
-webkit-transform: rotate(-225deg);
-ms-transform: rotate(-225deg);
transform: rotate(-225deg);
font-size: 2.5em;
font-weight: 100;
}
.accordionItem {
height: auto;
overflow: hidden;
max-height: 50em;
-webkit-transition: max-height 1s;
transition: max-height 1s;
}
@media screen and (min-width: 48em) {
.accordionItem {
/*max-height: 15em;*/
-webkit-transition: max-height 0.25s;
transition: max-height 0.25s;
}
}
.accordionItem.is-collapsed {
max-height: 0;
}
.no-js .accordionItem.is-collapsed {
max-height: auto;
}
.animateIn {
-webkit-animation: accordionIn 0.45s normal ease-in-out both 1;
animation: accordionIn 0.45s normal ease-in-out both 1;
}
.animateOut {
-webkit-animation: accordionOut 0.45s alternate ease-in-out both 1;
animation: accordionOut 0.45s alternate ease-in-out both 1;
}
@-webkit-keyframes accordionIn {
0% {
opacity: 0;
-webkit-transform: translateY(38px);
transform: translateY(38px);
}
100% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
}
@keyframes accordionIn {
0% {
opacity: 0;
-webkit-transform: translateY(38px);
transform: translateY(38px);
-webkit-transform-origin: 50% 0;
transform-origin: 50% 0;
/*
-webkit-transform: scale(0.9) rotateX(-60deg);
transform: scale(0.9) rotateX(-60deg);
-webkit-transform-origin: 50% 0;
transform-origin: 50% 0; */
}
100% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
}
@-webkit-keyframes accordionOut {
0% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
100% {
opacity: 0;
-webkit-transform: scale(0.9) rotateX(-60deg);
transform: scale(0.9) rotateX(-60deg);
}
}
@keyframes accordionOut {
0% {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1);
}
100% {
opacity: 0;
-webkit-transform: scale(0.9) rotateX(-60deg);
transform: scale(0.9) rotateX(-60deg);
}
}
<div class="container">
<h3 class="heading-primary">Q&A</h3>
<div class="accordion">
<dl>
<dt>
<a href="#accordion1" aria-expanded="false" aria-controls="accordion1" class="accordion-title accordionTitle js-accordionTrigger">First Accordion heading</a>
</dt>
<dd class="accordion-content accordionItem is-collapsed" id="accordion1" aria-hidden="true">
<p>Lorem ipsum dolor sit amet, consectetur <a href="http://www.google.com">Test</a>adipiscing elit. Morbi eu interdum diam. Donec interdum porttitor risus non bibendum. Maecejusto dui, sodales quis luctus a, iaculis eget mauris. </p>
<p>Aliquam dapibus, ante quis fringilla feugiat, mauris risus condimentum massa, at elementum r. Quisque blandit adipiscing erat vitae dapibus. Nulla aliquam magna nec elementum tincidunt.</p>
<p>Aliquam dapibus, ante quis fringilla </p>
</dd>
<dt>
<a href="#accordion1" aria-expanded="false" aria-controls="accordion1" class="accordion-title accordionTitle js-accordionTrigger">Second Accordion heading</a>
</dt>
<dd class="accordion-content accordionItem is-collapsed" id="accordion1" aria-hidden="true">
<p>Lorem ipsum dolor sit amet, consectetur <a href="http://www.google.com">Test</a>adipiscing elit. Morbi eu interdum diam. Donec interdum porttitor risus non bibendum. Maecenas sollicitudin eros in quam imperdiet placerat. Cras justo purus, rhoncus
nec lobortis ut, iaculis vel ipsum. Donec dignissim arcu nec elit faucibus condimentum. Donec facilisis consectetur enim sit amet varius. Pellentesque justo dui, sodales quis luctus a, iaculis eget mauris. </p>
<p>Aliquam dapibus, ante quis fringilla feugiat, mauris risus condimentum massa, at elementum libero quam ac ligula. Pellentesque at rhoncus dolor. Duis porttitor nibh ut lobortis aliquam. Nullam eu dolor venenatis mauris placerat tristique eget
id dolor. Quisque blandit adipiscing erat vitae dapibus. Nulla aliquam magna nec elementum tincidunt.</p>
</dd>
<dt>
<a href="#accordion1" aria-expanded="false" aria-controls="accordion1" class="accordion-title accordionTitle js-accordionTrigger">Third Accordion heading</a>
</dt>
<dd class="accordion-content accordionItem is-collapsed" id="accordion1" aria-hidden="true">
<p>Lorem ipsum dolor sit amet, consectetur <a href="http://www.google.com">Test</a>adipiscing elit. Morbi eu interdum diam. Donec interdum porttitor risus non bibendum. Maecenas sollicitudin eros in quam imperdiet placerat. Cras justo purus, rhoncus
nec lobortis ut, iaculis vel ipsum. Donec dignissim arcu nec elit faucibus condimentum. Donec facilisis consectetur enim sit amet varius. Pellentesque justo dui, sodales quis luctus a, iaculis eget mauris. </p>
<p>Aliquam dapibus, ante quis fringilla feugiat, mauris risus condimentum massa, at elementum libero quam ac ligula. Pellentesque at rhoncus dolor. Duis porttitor nibh ut lobortis aliquam. Nullam eu dolor venenatis mauris placerat tristique eget
id dolor. Quisque blandit adipiscing erat vitae dapibus. Nulla aliquam magna nec elementum tincidunt.</p>
</dd>
</dl>
</div>
</div>
| |
doc_23535973
|
In this case, there are two fields being saved when the last field is exited via tab. If I click "save" manually, both fields update correctly. If I use TAB, only the first field gets saved, and the old field doesn't save the new data. This tells me that somehow the "keydown" binding isn't seeing the new data.
If I debug locally and hover over "data" in the tabOut method, I see that the first field has new data, but the second field has old data.
fiddle: http://jsfiddle.net/PTSkR/18/
Any help would be much appreciated!
view:
<div class="span5 side-study-box">
<textarea data-bind="value: sides()[0].content"></textarea>
</div>
<div class="span5 side-study-box">
<textarea data-bind="value: sides()[1].content, event: { keydown: tabOut }"></textarea>
</div>
tabOut function:
self.tabOut = function (data, event) {
if (event.keyCode == 9) {
debugger;
self.save();
};
return true;
};
A: Have you tried adding "valueUpdate:'afterkeydown'" bingings to your textboxes?
| |
doc_23535974
|
<img
class="bowgart"
id="bowgart"
src="C:\Users\jbrir\Documents\BowgartWebsite2\images\bowgart.png"
alt="Bowgart"
/>
<script>
function imgOpen() {
document.getElementById("bowgart").src = "C:UsersjbrirDocumentsBowgartWebsite2imagesBowgart_open.jpeg";
}
</script>
A: The src needs to be a valid URL. You're missing the file: URL scheme and all the / delimiters in the pathname.
function imgOpen() {
document.getElementById("bowgart").src =
"file:///C:/Users/jbrir/Documents/Bowgart/Website2/images/Bowgart_open.jpeg";
}
A: I recommend using this code:
<!DOCTYPE html>
<html>
<body>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>
</body>
</html>
The way how this code works is that when you click the button it changes the source of the image(you do have to have both images) and applies that to the image. And if that was confusing to you then here is a simpler way of saying that: if the image was off and you click the 'on' button it will change to image to on else it does not do anything and the same if it was on. And this is just an example so apply this to your images.
| |
doc_23535975
|
I now have 5 different if statements
with open('stuff.txt', 'r') as f:
lines = f.read().splitlines()
for line in lines:
if line == str(sameDay):
bag.append(line)
if line == str(threeDaysAgo):
bag.append(line)
if line == str(weekAgo):
bag.append(line)
if line == str(monthAgo):
bag.append(line)
if line == str(threeDaysAgo):
bag.append(line)
A: Better than having many if statements, and also more efficient that calling on append multiple times.
variables = set(map(str, [sameDay, threeDayAgo, weekAgo...]))
def check_variables(lines):
for line in lines:
if line in variables:
yield line
Edit: Made variables into a set since it runs in faster than a list. Useful if lines is really long.
A: if line in [str(x) for x in [sameDay, threeDaysAgo, weekAgo, monthAgo]]:
bag.append(line)
You might want to save the list in a variable beforehand to make this a bit more clean.
A: You can remove define a list of VALID_LINES and check if the read line is in the list. If YES, then append to the bag.
Moreover, we can use list comprehension for efficiency.
VALID_LINES = [str(sameDay), str(threeDaysAgo), str(weekAgo), str(monthAgo), str(threeDaysAgo)]
with open('stuff.txt', 'r') as f:
lines = f.read().splitlines()
[bag.append(line) for line in lines if line in VALID_LINES]
A: you can use:
acceptable = {str(e) for e in [sameDay, threeDaysAgo, monthAgo, hreeDaysAgo]}
with open('stuff.txt', 'r') as f:
bag = [line for line in f.readlines() if line in acceptable ]
A: As python does not have switch-case statements, so you can use the following function as switch case. And you can implement your function return logic as per your requirement. As you are appending line every time so this function returns the same line every time.
def f(line):
return {
'sameDay': line,
'threeDaysAgo': line,
'weekAgo':line,
'monthAgo':line,
'threeDaysAgo':line
}.get(line)
bag = []
for line in lines:
bag.append(f(line))
| |
doc_23535976
|
Why they use syntax of creating new object:
myDelegate = new AddListItem(AddListItemMethod);
instead of assigment
myDelegate = AddListItemMethod;
What is the difference between these expressions? What is the meaning of expression new AddListItem(...) ?
Whole code:
public class MyFormControl : Form
{
public delegate void AddListItem();
public AddListItem myDelegate;
private Button myButton;
private Thread myThread;
private ListBox myListBox;
public MyFormControl()
{
myButton = new Button();
myListBox = new ListBox();
myButton.Location = new Point(72, 160);
myButton.Size = new Size(152, 32);
myButton.TabIndex = 1;
myButton.Text = "Add items in list box";
myButton.Click += new EventHandler(Button_Click);
myListBox.Location = new Point(48, 32);
myListBox.Name = "myListBox";
myListBox.Size = new Size(200, 95);
myListBox.TabIndex = 2;
ClientSize = new Size(292, 273);
Controls.AddRange(new Control[] {myListBox,myButton});
Text = " 'Control_Invoke' example";
myDelegate = new AddListItem(AddListItemMethod);
}
static void Main()
{
MyFormControl myForm = new MyFormControl();
myForm.ShowDialog();
}
public void AddListItemMethod()
{
String myItem;
for(int i=1;i<6;i++)
{
myItem = "MyListItem" + i.ToString();
myListBox.Items.Add(myItem);
myListBox.Update();
Thread.Sleep(300);
}
}
private void Button_Click(object sender, EventArgs e)
{
myThread = new Thread(new ThreadStart(ThreadFunction));
myThread.Start();
}
private void ThreadFunction()
{
MyThreadClass myThreadClassObject = new MyThreadClass(this);
myThreadClassObject.Run();
}
}
// The following code assumes a 'ListBox' and a 'Button' control are added to a form,
// containing a delegate which encapsulates a method that adds items to the listbox.
public class MyThreadClass
{
MyFormControl myFormControl1;
public MyThreadClass(MyFormControl myForm)
{
myFormControl1 = myForm;
}
public void Run()
{
// Execute the specified delegate on the thread that owns
// 'myFormControl1' control's underlying window handle.
myFormControl1.Invoke(myFormControl1.myDelegate);
}
}
A: There is no difference.
The new syntax is what was required long time ago and since then they made c# compiler smart enough to create this code for you when you assign method to delegate variable.
| |
doc_23535977
|
the two function looks like this
//mapfun
{ "_id" : "mapfun","value" : { "code" : "function(){var criteria; if(this.speed > 70 ){ criteria="overspeed";emit(criteria,this.speed); } }" } }
//reducefun
{ "_id" : "reducefun", "value" : { "code" : "function(key,speed){ var total=0; for(var i=0;i<speed.length;i++){ total=total+speed[i]; } return total/speed.length; }" } }
and my mapreducecommand looks like this
MapReduceCommand command=new MapReduceCommand(collection, map, reduce, null, MapReduceCommand.OutputType.INLINE, null);
MapReduceOutput output=collection.mapReduce(command);
i have passed the map and reduce function as strings in which i have called the mapfun and reducefun respectively
and it looks like this
String map = "function (){var x=mapfun();"
+ "return x;};";
String reduce = "function(key, speed) {var y=reducefun(key,speed);"
+ "return y;};";
what am i doing wrong here and how to correct this kindly help me with this.
A: The underlying problem is that the this variable is reassigned for each function call.
To demonstrate, I ran a short test from the mongo shell.
Fist create a collection containing 1 document:
MongoDB Enterprise replset:PRIMARY> db.maptest.find({},{_id:0})
{ "canary" : "tweet" }
Then create a stored function that will take an argument emit 2 values, one using this and one using the passed argument:
MongoDB Enterprise replset:PRIMARY> db.system.js.find()
{ "_id" : "testfun", "value" : { "code" : "function(arg){emit(\"this.canary\",this.canary),emit(\"arg.canary\",arg.canary)}" } }
Then use the stored function in a mapReduce call:
MongoDB Enterprise replset:PRIMARY> db.maptest.mapReduce(function(){testfun(this)},function(a,b){return {a:a,b:b}},{out:{inline:1}})
{
"results" : [
{
"_id" : "arg.canary",
"value" : "tweet"
},
{
"_id" : "this.canary",
"value" : undefined
}
],
...
As you can see, this.canary was undefined, but arg.canary contained the value from the input document.
The mapReduce framework assigns this to the document currently being examined when calling the map function. When the stored function is called from within the map function it gets its very own this. However, by calling the function as testfun(this) the original this context of the map function is provided to the stored function as an argument.
| |
doc_23535978
|
This should be possible, because ZAP is referenced as a tool for testing session management in the OWASP Testing Guide:
Tools
OWASP Zed Attack Proxy Project (ZAP) - https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project - features a session token analysis mechanism.
But I can't find any documentation how to test session managment.
Note: There's a lot of documentation regarding how to add authentication to ZAP but not how to test it.
A: There are several features included in ZAP related to testing session management.
You need the following AddOns (https://github.com/zaproxy/zap-core-help/wiki/HelpUiDialogsManageaddons)
*
*Addon Active Scanner Rules (beta)
*Addon Passive scanner rules (alpha)
*Addon Passive scanner rules (beta)
*Addon Passive scanner rules (release)
*Addon Token generation and analysis
*Addon ViewState
These AddOns provide the following functionality...
AddOn Active Scanners
*
*Session Fixation
*Cookie Slack Detector (Reveal areas where session cookies are not actually enforced)
AddOn Passive Scanners
*
*Insecure JSF ViewState
*Viewstate Scanner
*Weak Authentication Method
*Cookie no httpOnly flag
*cookie without secure flag
*session id in url rewrite
Addon Token generation and analysis
Allows you to generate and analyze pseudo random tokens, such as those used for session handling or CSRF protection
Addon ViewState
ASP/JSF ViewState Decoder and Editor
MainMenuBar > Tools > Encode/Decode/Hash...
Could help to identify meaningful Tokens
The following Plugins are more related to authentication/authorization than session management but...
AddOn SAML Extension
Detect, Show, Edit, Fuzz SAML requests
AddOn Access Control Testing
Adds a set of tools for testing access control in web applications
| |
doc_23535979
|
A: When dinosaurs ruled the Earth and some professional programmers actually used Turbo C, the cursor support was handled through routines in an include file called conio.h.
http://en.wikipedia.org/wiki/Conio.h
You won't find a lot of Internet-era writings about this. But I managed to find a reference to someone using this in an online document:
/* Program to display text using special functions*/
#include <conio.h>
main (){
int n,m,;
/* clears the screen */
clrscr ( );
/* sets the text mode to 80 columns color*/
textmode (3);
/* SETS THE TEXT COLOR*/
textcolor (4);
/* sets the text background color */
textbackground (2);
/* Positions to 5th row and 14th column*/
gotoxy (5,15);
printf ("Enter two numbers:");
scanf ("%d %d", &n, &m);
gotoxy (10,15);
printf ("Entered numbers are %d and %d \n\n", n,m);
}
It's not clear if you mean you want to redefine keys such that while your program is running, when a certain key is pressed by the user, it produces a different character output. If so you will probably want to use something like bioskey()...because getch() only reads characters and not things like function keys or modifiers:
http://www.softwareandfinance.com/Turbo_C/bioskey.html
A: You might take a look at the gotoxy(int x, int y) function, which is not ANSI C, but a Borland extension in Turbo C. It places the cursor at the coordinate (x, y) in a text mode display.
As far as redefining keystrokes, are you looking at doing this within your program or within the ide? If within your program, you can use the scan code returned by getchar() and alter it before re-outputting it with putchar(char c). As far as defining key bindings for ide functions, I THINK (it's been a long time) the user interface allowed that within the menus.
Sorry I couldn't be of more help.
| |
doc_23535980
|
A: Shellcode are machine code instructions contained in data. They are used when exploiting buffer overrun and other vulnerabilities that cause the data you supply to be copied over existing code, or allow you to set a return address to a buffer filled with your shellcode.
Debugging kernel mode shellcode would require a kernel debugger. Place a breakpoint in the vulnerable kernel code, perform your exploit, and single step as control transfers to the shellcode.
| |
doc_23535981
|
screen shot
https://i.stack.imgur.com/lEs13.jpg
please check above image for source code.
here top of page i am getting empty space and 15 line coding has been starting
Please any once can suggest, how my code start with 1 st line.
A: The white space lines must be removed from the header template view where your header view is attached to body view.
Check the Controller first, then find which header is rendered for that page where you see the empty lines.
I hope it will help!
| |
doc_23535982
|
My XML:
<table-opt>
<tablerow>
<table_data>test</table_data>
</tablerow>
<tablerow>
<table_data>test2</table_data>
</tablerow>
<tablerow>
<table_data>test3</table_data>
</tablerow>
</table-opt>
And my XSL:
<xsl:template name="table-opt">
<xsl:variable name="countdata" select="count(.//tablerow/table_data)"></xsl:variable>
<table border="0" cellpadding="0" cellspacing="0" class="fullwidth" width="640px">
<tr>
<td width="640px" align="center">
<xsl:value-of select="$countdata"/>
</td>
</tr>
</table>
</xsl:template>
So now it gives me the answer 3. I do understand why, but I actually want the answer 1 because I have only one table_data in each tablerow. How could I do this?
I know that if in one tablerow are two table_data I would have a problem. But forget this option, it will never happen.
A: I got it! Just put the $countdata variable in a for-each for each tablerow. I hope I can help other users with a similar problem.
| |
doc_23535983
|
Consider using a System Image with Google APIs to enable testing with Google Play Services.
Is this image not available yet? or am I missing something? I dont see it in the SDK Manager yet.
A: As of SDK Tools 25.1.7 and Intel x86 Atom_64 System Image Rev. 6, it appears that there is no longer a separate emulator image for the Google APIs - instead, the normal emulator image now includes the Google APIs by default. So, the message shown in the "Recommendation" section when creating an AVD appears to be old/incorrect.
I was able to run this project (using gradlew installObaGoogleDebug), which requires Google Play Services for maps and other items, by selecting Nougat / API Level 24 / x86_64 / Android 7.0.
EDIT Nov. 3rd 2016
It appears this was a temporary issue with the emulator image. As of SDK Tools 25.2.2 and Intel x86 Atom_64 System Image Rev. 7, when I try to run the same app on the same emulator image (API Level 24) I created above, it now says "OneBusAway relies on Google Play Services, which is not supported on your device".
However, it looks like there is now an API Level 25 (Android 7.1.1) emulator w/ ABI x86_64 available for download that does explictly include the Google APIs - see area circled in red below (note that the update message still seems to erronouesly appear):
A: I had the same issue recently, I think it's probably a bug with the tool.
I was able to solve it by downloading the x86_64 version, and then it allowed me to use both the N x86 and N x86_64 emulator images.
| |
doc_23535984
|
Thanks
paypal.pay(message.id, args[0], 'Invoice', 'USD', function(err, url) {
if(err) {
console.log(err);
return;
}
message.channel.send({embed: {
color: 0x28d651,
title: "Slashy Payment",
fields: [
{
name: "Invoice Amount",
value: "$" + args[0],
inline: true
},
{
name: "Invoice Client",
value: message.author.username,
inline: true
},
{
name: "Invoice Status",
value: "Pending..."
},
{
name: "Payment Link",
value: '[Pay here](' + url + ')'
}
],
timestamp: new Date(),
footer: {
icon_url: bot.user.avatarURL,
text: "© Slashy 2018"
}
}
});
});
A: Just for anyone wanting to know how I managed to do it in the end just store the message.channel.id in the URL for the paypal return link and when they get to the page save the info into a database with the channel id and just keep checking the database every 5 seconds in the channel if the item has been marked as paid in the database. Really cool fix that seems to work fine
A: Just another solution for you, instead of polling, just create an express webserver or open a tcp socket. Yes php does tcp sockets as well. Anyways, once paypal returns its message to your php server, have the php script send a request to your node.js express server that is also running your bot. I don't know how option people will be purchasing via your bot, but it seems like a good alternative than to waste some cpu time if loads of people start buying :D but hey, that's a good problem right?
| |
doc_23535985
|
float time(time) ;
time:standard_name = "time" ;
time:long_name = "time" ;
time:units = "hours since 1900-01-01 00:00:00.0" ;
time:calendar = "gregorian" ;
time:axis = "T" ;
With the following command
ncdump -tv time infile.nc
time format looks like
"2009-12-31 22"
I want to make it so that it is like
"2020-12-31 22:00"
How do I achieve this with either nco or cdo??
A: If the file is not huge you could try
cdo -outputtab,date,time infile.nc | sort | uniq
I think it also assumes that time is the unlimited dimension, and may produce errors otherwise.
| |
doc_23535986
|
I'm working on SSRS Report, It shows datepicker in Firefox browser as well as in IE Browser but not showing in Google Chrome. Can anyone please help me.
ReportView.aspx
<div id="divReportViewer" runat="server" style="overflow: auto;">
<rsweb:ReportViewer ID="rvReports" runat="server" ProcessingMode="Remote" AsyncRendering="true" ShowBackButton="false" ShowExportControls="true" ShowPrintButton="false">
</rsweb:ReportViewer>
</div>
I don't want to use Jquery Calendar. I want to use SSRS date picker. Thanks!
A: I recently ran into something very similar myself (an SSRS report not working properly in Chrome after it was deployed).
As was the case with you, it worked in IE, so I had resigned myself to being forced to use IE for reports.
That is until I changed versions of SQL from 2008 to 2014, and to my surprise, the report viewer then worked in Chrome.
So I suggest an upgrade (because who wants to use IE?!)
| |
doc_23535987
|
Copied from the code generated on the AWS console to include in my code:
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;
namespace AWSLambda
{
public class Function
{
private static string Key1Value;
// Read values once, in the constructor
public Function()
{
// Decrypt code should run once and variables stored outside of the
// function handler so that these are decrypted once per container
Key1Value = DecodeEnvVar("ConnString").Result;
}
private static async Task<string> DecodeEnvVar(string envVarName)
{
// Retrieve env var text
var encryptedBase64Text = Environment.GetEnvironmentVariable(envVarName);
// Convert base64-encoded text to bytes
var encryptedBytes = Convert.FromBase64String(encryptedBase64Text);
// Construct client
using (var client = new AmazonKeyManagementServiceClient())
{
// Construct request
var decryptRequest = new DecryptRequest
{
CiphertextBlob = new MemoryStream(encryptedBytes),
};
// Call KMS to decrypt data
var response = await client.DecryptAsync(decryptRequest);
using (var plaintextStream = response.Plaintext)
{
// Get decrypted bytes
var plaintextBytes = plaintextStream.ToArray();
// Convert decrypted bytes to ASCII text
var plaintext = Encoding.UTF8.GetString(plaintextBytes);
return plaintext;
}
}
}
public void FunctionHandler()
{
Console.WriteLine("Encrypted environment variable Key1 = " + Key1Value);
}
}
}
A: I guess I found the answer. The encryption key does not stay on the lambda. It is a one off operation to encrypt the values on the console. Refreshed the page and the link to KMS is gone, or login with another user to only see encrypted values on the env var, with no encryption key attached.
| |
doc_23535988
|
$sql2 = "SELECT * FROM ".$table_name." WHERE id=".$_GET['new_time'];
$result2 = mysqli_query($conn, $sql2);
$rows = mysqli_fetch_assoc($result2);
$mobile_number = $rows['mobile_number'];
// Create instance with key
$key = 'AIzaSyD1tPfs4s2dYYHMkCOqNZoVsTkDyud-9Yg';
$googer = new GoogleURLAPI($key);
$message = lang_content(98, $rows['preferred_language'])." ".$shortDWName;
$send_sms($mobile_number,$message,$city_id);
}
If someone triggers the new_time, I get this error.
send_sms is a function to send a message.
A: You do not need to add $ in function name while calling that function:
just use send_sms($mobile_number,$message,$city_id);
A: you can call function by calling its name
send_sms($mobile_number,$message,$city_id);
or
declare a variable and make a function call in that variable
$sendsms=send_sms($mobile_number,$message,$city_id);
| |
doc_23535989
|
However, when I compile and run the program, it seems like it can store more than that.
I only get the "Segmentation fault" error when I entered "ABCDEFGHIJKLMNOPQRSTUVWXY" which is clearly more than 3 char.
May I know why?
p/s: Yeah, I know "gets" function is dangerous and not recommended to use. I'm just curious why it can keep more data than it should.
user@box:~/c$ cat -n putsgets.c
1 #include <stdio.h>
2
3 int main()
4 {
5 char str[3];
6 puts("Enter a line of text: ");
7 gets(str);
8 puts("\nYou entered: ");
9 puts(str);
10 return 0;
11 }
user@box:~/c$
user@box:~/c$ gcc putsgets.c -o putsgets
putsgets.c: In function ‘main’:
putsgets.c:7:2: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration]
gets(str);
^~~~
/tmp/cclFmZp2.o: In function `main':
putsgets.c:(.text+0x1f): warning: the `gets' function is dangerous and should not be used.
user@box:~/c$
user@box:~/c$ ./putsgets
Enter a line of text:
ABC
You entered:
ABC
user@box:~/c$ ./putsgets
Enter a line of text:
ABCD
You entered:
ABCD
user@box:~/c$
Next
user@box:~/c$ ./putsgets
Enter a line of text:
ABCDE
You entered:
ABCDE
user@box:~/c$ ./putsgets
Enter a line of text:
ABCDE
You entered:
ABCDE
user@box:~/c$ ./putsgets
Enter a line of text:
ABCDEF
You entered:
ABCDEF
user@box:~/c$ ./putsgets
Enter a line of text:
ABCDEFGHIJKLMN
You entered:
ABCDEFGHIJKLMN
Finally, Segmentation fault error occurred when I entered ABCDEFGHIJKLMNOPQRSTUVWXY (last line)
user@box:~/c$ ./putsgets
Enter a line of text:
ABCDEFGHIJKLMNOPQRSTU
You entered:
ABCDEFGHIJKLMNOPQRSTU
user@box:~/c$ ./putsgets
Enter a line of text:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
You entered:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Segmentation fault
user@box:~/c$ ./putsgets
Enter a line of text:
ABCDEFGHIJKLMNOPQRSTUVWXY
You entered:
ABCDEFGHIJKLMNOPQRSTUVWXY
Segmentation fault
user@box:~/c$
A: As you likely know, C does not check for memory safety. Utilities such as valgrind can really help with that, though.
Your operating system is giving your program a bit more memory than it requested, and it only finds segmentation faults when you go outside one of that memory.
How does a segmentation fault work internally (kernel/hardware)?
A: It's undefined behaviour because C and C++ does not check array bound.
A: In C you can add more cbaracters to an array than declared, because no runtime checks are performed. What you do is called buffer overrun.
If such code accepts data over a network connection, then a hacker could exploit this to run arbitrary machine code!
However, in java and C# runtime checks are performed and a buffer overrun causes a OutOfRangeExeption. These checks are performed by the java virtual machine.
Good question and keep up your curiousity.
| |
doc_23535990
|
I am creating a bank account with the test routing/account number. I then create a verification and finally confirm it using amount_1 = 1 and amount_2 = 1.
If I look in my marketplace logs everything looks great. All requests are 200, and I see the response from the confirmation as "succeeded" except the marketplace dashboard still shows the verification as pending.
If I try to debit the account it fails because
funding-source-not-debitable: Funding instrument cannot be debited
which I've been told is because it's not verified.
I'm not sure what else to try as the logs show it's working, but everything else acts as if it's not verified.
My Ruby code looks like this:
@account = Balanced::BankAccount.fetch("/bank_accounts/#{balanced_id}")
#for test marketplace auto verify
if !Rails.env.production?
verification = @account.verify
verification.confirm(
amount_1 = 1,
amount_2 = 1
)
end
A: That is the correct syntax, however, I believe you are later associating this bank account to a customer. Doing so resets the can_debit field to False. You should therefore associate your customer before creating a verification.
| |
doc_23535991
|
This is what i have so far:
<Autosuggest
suggestions={options}
onSuggestionsFetchRequested={fetchOptions}
onSuggestionsClearRequested={() => setOptions([])}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
/>
I have all the options on a prop and i want to filter those options to show the ones matching the input, this is how i'm filtering right now:
const fetchOptions = async ({ value }) => {
setSelected(null);
value = value.toLowerCase();
const results = props.completeOptions.filter(
(v) => v.label.toLowerCase().indexOf(value) != -1
);
setOptions(limit(results)); //Here i'm setting the options hook that i use on the suggestions
};
This is the value of completeOptions prop that i have on redux:
[
{
"id": "1",
"label": "33 Red Case"
},
{
"id": "2",
"label": "Blue Case"
},
{
"id": "3",
"label": "1 Green Case"
},
...
]
Now, this is working perfectly if i input for example "Case" (this shows the 3 labels), if i use "33" (shows the first one), but if i input "33 case" doesn't show anything and it should show the first option.
How can i solve this? Is it convenient to split the value and search each one, is it better to search the whole string together?
A: Your filter logic looks fine, when we just want a check whether substring is present then we should go with
v.label.toLowerCase().split(" ").includes(value)
Or
v.label.toLowerCase().split(" ").some(val => val.includes(value)
In above case we are splitting string to array and matching substring with each of token
indexOf handles substring checking little different and can cause undesired results.
A: Since you are looking for full search word match. You can use every in javascript to check search word and return true when all the search word get a match. You can check this code.
const searchData = value.toLowerCase().split(" ");
const results = props.completeOptions.filter(v => searchData.every(word => v.label.toLowerCase().includes(word)));
| |
doc_23535992
|
I can also request the list of brands which has the brands and their IDs
I've been trying to display the actual name in my template and not the ID and I keep running into problems, the data is not being reactive propery and i can only get it to load sometimes after vite does a HMR update
I also want to do this with an array of vendor objects which contain the ID and name of each of our vendors
(each product has an array of vendor IDS from which this product is available to purchase)
is thee something in missing in my code to make this work or am i just being an idiot
<script setup>
import priceGraph from "../components/priceGraph.vue";
import { ref, computed } from "vue";
import { useProductsStore } from "../stores/products";
import { useRoute } from 'vue-router'
import axios from 'axios'
const store = useProductsStore();
const route = useRoute()
let id = route.params.id
let link = "http://127.0.0.1:8000/products/" + id
const deets = ref({
name: "Loading",
description: "Loading",
brand: "loading", // this is brand ID
brandname: "Loading", // this needs to be the brand name to be rendered
sku: "Loading",
asin: "Loading",
})
store.fetchProducts()
store.fetchVendors()
store.fetchBrands()
const vendorNames = store.vendors
const brandNames = store.brands
console.log(vendorNames, brandNames)
async function getDeets(link) {
try {
const data = await axios.get(link)
deets.value = data.data;
console.log(deets.value)
} catch (error) {
console.log(error);
}
};
getDeets(link)
const brand = computed(() => brandNames.find((b) => b.id === deets.brand))
console.log(brand.value)
</script>
<template>
<div class="container">
<div class="back">
<button @click="$router.go(-1)">Back</button>
</div>
<div class='deets'>
<h1>Product Details</h1>
<hr>
<!-- <h2>ID: {{ deets.id }}</h2> -->
<h2>Name: {{ deets.name }}</h2>
<h3>Description: {{ deets.description }}</h3>
<h2>Sku: {{ deets.sku }}</h2>
<h3>brandID: {{ deets.brand }}</h3>
<h3>brand name: {{ deets.brandname }}</h3>
<h3>Asin: {{ deets.asin }}</h3>
<h3>Date added: {{ deets.added }}</h3>
<h3>Last updated: {{ deets.updated }}</h3>
<hr>
</div>
</div>
</template>
| |
doc_23535993
|
Exception has occurred.
PlatformException (PlatformException(sign_in_required, com.google.GIDSignIn, The operation couldn’t be completed. (com.google.GIDSignIn error -4.)))
Please have a look into below mentioned code snippet for main.dart file
// Copyright 2019 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'dart:convert' show json;
import "package:http/http.dart" as http;
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: <String>[
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
void main() {
runApp(
MaterialApp(
title: 'Google Sign In',
home: SignInDemo(),
),
);
}
class SignInDemo extends StatefulWidget {
@override
State createState() => SignInDemoState();
}
class SignInDemoState extends State<SignInDemo> {
GoogleSignInAccount _currentUser;
String _contactText;
@override
void initState() {
super.initState();
_googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
setState(() {
_currentUser = account;
});
if (_currentUser != null) {
_handleGetContact();
}
});
_googleSignIn.signInSilently();
}
Future<void> _handleGetContact() async {
setState(() {
_contactText = "Loading contact info...";
});
final http.Response response = await http.get(
'https://people.googleapis.com/v1/people/me/connections'
'?requestMask.includeField=person.names',
headers: await _currentUser.authHeaders,
);
if (response.statusCode != 200) {
setState(() {
_contactText = "People API gave a ${response.statusCode} "
"response. Check logs for details.";
});
print('People API ${response.statusCode} response: ${response.body}');
return;
}
final Map<String, dynamic> data = json.decode(response.body);
final String namedContact = _pickFirstNamedContact(data);
setState(() {
if (namedContact != null) {
_contactText = "I see you know $namedContact!";
} else {
_contactText = "No contacts to display.";
}
});
}
String _pickFirstNamedContact(Map<String, dynamic> data) {
final List<dynamic> connections = data['connections'];
final Map<String, dynamic> contact = connections?.firstWhere(
(dynamic contact) => contact['names'] != null,
orElse: () => null,
);
if (contact != null) {
final Map<String, dynamic> name = contact['names'].firstWhere(
(dynamic name) => name['displayName'] != null,
orElse: () => null,
);
if (name != null) {
return name['displayName'];
}
}
return null;
}
Future<void> _handleSignIn() async {
try {
await _googleSignIn.signIn();
} catch (error) {
print(error);
}
}
Future<void> _handleSignOut() => _googleSignIn.disconnect();
Widget _buildBody() {
if (_currentUser != null) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ListTile(
leading: GoogleUserCircleAvatar(
identity: _currentUser,
),
title: Text(_currentUser.displayName ?? ''),
subtitle: Text(_currentUser.email ?? ''),
),
const Text("Signed in successfully."),
Text(_contactText ?? ''),
RaisedButton(
child: const Text('SIGN OUT'),
onPressed: _handleSignOut,
),
RaisedButton(
child: const Text('REFRESH'),
onPressed: _handleGetContact,
),
],
);
} else {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
const Text("You are not currently signed in."),
RaisedButton(
child: const Text('SIGN IN'),
onPressed: _handleSignIn,
),
],
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Google Sign In'),
),
body: ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: _buildBody(),
));
}
}
I want to user firebase as my backend. But before doing so this itself is not working for me.
I could see Flutter google sign in stay logged in : here also they are using the same technique.
A: According to the package requirements:
To access Google Sign-In, you'll need to make sure to register your application (with firebase).
You don't need to include the google-services.json file in your app unless you are using Google services that require it. You do need to enable the OAuth APIs that you want, using the Google Cloud Platform API manager. For example, if you want to mimic the behavior of the Google Sign-In sample app, you'll need to enable the Google People API.
Make sure you've filled out all required fields in the console for OAuth consent screen. Otherwise, you may encounter APIException errors.
A: That error means there are no auth token in the keychain, I faced it once and solve with this answer, I copy and send the code I used below, also you can check other solutions from that thread.
if GIDSignIn.sharedInstance().hasAuthInKeychain() == true{
GIDSignIn.sharedInstance().signInSilently()
}
else{
GIDSignIn.sharedInstance().signIn()
}
| |
doc_23535994
|
Returning the value of $this->request->data shows this:
Array
(
[Order] => Array
(
[id] =>
[customer_id] => 4711
[orderDate] => Array
(
[month] => 01
[day] => 14
[year] => 2014
)
...
)
[ArticleOrder] => Array
(
[article_id] => Array
(
[0] => 2002
)
[quantity] => Array
(
[0] => 99
)
)
)
The Array [ArticleOrder] hasn't been saved in the Database. In my Controller I tried saveAll (yes deep => true), saveMany, saveAssociated...
Here is the Controller:
public function add() {
$this->set('customers', $this->Order->Customer->find('list')); //Auflösung der Schlüssel
//$this->set('articles', $this->Order->ArticleOrder->Article->find('list'));
if(!empty($this->request->data)) {
$this->Order->create();
pr($this->data);
if($this->Order->ArticleOrder->saveAll($this->request->data, array('deep' => true))) {
$this->Session->setFlash("Die Bestellung wurde gespeichert!");
$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash('Die Bestellung konnte nicht gespeichert werden.');
}
}
}
Please help me ... i'm despaired...
Greetings from Germany
A: The array is wrong? I think it should look like this:
'ArticleOrder' => array(
array('article_id' => 2002, 'quantity' => 99),
array('article_id' => 3151, 'quantity' => 14),
/* ... */
);
Check your code that generates the form or data structure.
See http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array
A: I solved the problem :-)
Here is the code of the controller:
public function add() {
$this->set('customers', $this->Order->Customer->find('list')); //Auflösung der Schlüssel
//$this->set('articles', $this->Order->ArticleOrder->Article->find('list'));
if(!empty($this->request->data)) {
$this->Order->create();
$data = array(
'Order' => $this->request->data['Order'],
'ArticleOrder' => array()
);
for($i = 0; $i< count($this->request->data['ArticleOrder']['article_id']); $i++) {
$data['ArticleOrder'][] = array(
'article_id' => $this->request->data['ArticleOrder']['article_id'][$i],
'quantity' => $this->request->data['ArticleOrder']['quantity'][$i]
);
}
if($this->Order->saveAssociated($data, array('deep'=>true))) {
$this->Session->setFlash("Die Bestellung wurde gespeichert!");
$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash('Die Bestellung konnte nicht gespeichert werden.');
}
}
}
I just formatted the array in the for-block
Thank you
| |
doc_23535995
|
Below is my code:
ax=nps_funding_month[35:][nps_funding_month['count_ratings']>=100].set_index('funding_month')['nps_percentage'].\
plot(kind='line',color='green',label='NPS')
plt.ylabel('Net Promoter Score')
ax=nps_funding_month[35:][nps_funding_month['count_ratings']>=100].set_index('funding_month')['count_ratings'].\
plot(kind='bar',secondary_y=True,label='Count of Ratings')
plt.ylabel('Count Ratings')
plt.legend()
plt.title('Net Promoter Score by Funding Month\n(Only Funding Months with at Least 100 Reviews)')
A: The following code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.DataFrame({"x" : np.arange(5),
"a" : np.exp(np.linspace(3,5,5)),
"b" : np.exp(-np.linspace(-1,0.5,5)**2)})
ax=df.plot(x="x", y="a", kind='line',color='green',label='NPS')
plt.ylabel('Net Promoter Score')
ax2 = df.plot(x="x", y="b", kind='bar',secondary_y=True,label='Count of Ratings', ax=ax)
plt.ylabel('Count Ratings')
plt.title('Superlongtitle that is not needed')
plt.show()
produces
Note that the first axes is given as argument to the second pandas plot (ax=ax) and no legend is added via pyplot (it comes automatically through pandas).
The problem may then be that the legend is hidden by the bars. The reason for that is that the legend resides in the first (lower) axes. There are two options.
*
*We could move it to the secondary axes and then also change its location.
leg = ax.get_legend()
leg.remove() # remove it from ax
ax2.add_artist(leg) # add it to ax2
leg._set_loc(4)
Where the the loc 4 means "lower left" and is one of the codes to place the legend.
*We can move it out of the plot, (as in How to put the legend out of the plot)
leg._set_loc(2)
leg.set_bbox_to_anchor((1.1,1))
ax.figure.subplots_adjust(right=0.6) # make space for the legend outside
| |
doc_23535996
|
echo"<form action='' method='GET' class='form-inline' role='form'>";
$query = "SELECT Naam FROM Soortmaaltijd"; //Alle soortmaaltijden ophalen
$result= mysql_query($query) or die(mysql_error());
echo"<div class='row'>";
echo"<div class='form-group' >";
echo"<label for='soortmaaltijd'>Soort maaltijd</label></br>";
echo"<select name='Soortmaaltijd' class='form-control' id='soortmaaltijd'>";
echo"<option value=''>Alle</option>";
while($row=mysql_fetch_array($result)) {
echo"<option value='$row[SoortmaaltijdID]'>$row[Naam]</option>";
}
echo"</select>";
echo"</div>";
$query = "SELECT * FROM Soortgerecht"; //Alle soortgerechten ophalen
$result= mysql_query($query) or die(mysql_error());
echo"<div class='form-group' >";
echo"<label for='soortgerecht'>Soort gerecht</label></br>";
echo"<select name='soortgerecht' class='form-control' id='soortgerecht'>";
echo"<option value=''>Alle</option>";
while($row=mysql_fetch_array($result)) {
echo"<option value='$row[SoortgerechtID]'>$row[Naam]</option>";
}
echo"</select>";
echo"</div>";
echo"<div class='form-group' >";
echo"<label for='moeilijkheid'>Moeilijkheid</label></br>";//Moeilijkheid
echo"<select name='moeilijkheid' class='form-control' id='moeilijkheid'>";
echo"<option value=''>Alle</option>";
echo"<option value='1'>1</option>";
echo"<option value='2'>2</option>";
echo"<option value='3'>3</option>";
echo"</select>";
echo"</div>";
echo"<div class='form-group' >";
echo"<label for='tijd'>Max bereidingstijd</label></br>";//Max bereidingstijd
echo"<select name='tijd' class='form-control' id='tijd'>";
echo"<option value=''>Alle</option>";
echo"<option value='5'><5</option>";
echo"<option value='10'><10</option>";
echo"<option value='15'><15</option>";
echo"<option value='20'><20</option>";
echo"<option value='25'><25</option>";
echo"<option value='30'><30</option>";
echo"</select>";
echo" <button type='submit' name='filter' class='btn btn-primary btn-lg-2'>Filter</button>";
echo"</div>";
echo"</div>";
echo"</form>"; ?>
But how can I contruct a query that uses all the variables even when some filter settings aren't changed. It is possible to create 20 queries but that costs too much time. Is it possible to create something like this:
WHERE Tijd = $tijd AND Soortmaaltijd = $soortmaaltijd AND Soortgerecht = $soortmaaltijd AND Moeilijkheid = $moeilijkheid
But if some value is not set in the filter like 'Tijd', 'Tijd' has a standard value?
A: You probably just need to construct your full WHERE in advance so that instead of sending 4 vars to your query you send a single WHERE statement.
Example 1 (constructing a $where var which concatenates your conditions):
$where = "WHERE ";
$count = 0;
if ( !empty($tijd) ) {
$where .= "`Tijd` = " . $tijd . " ";
++$count;
} elseif( !empty($soortmaaltijd) ) {
if ($count == 0)
$where .= "`Soortmaaltijd` = " . $soortmaaltijd . " ";
else
$where .= "AND `Soortmaaltijd` = " . $soortmaaltijd . " ";
++$count;
} elseif( !empty($soortgerecht) ) {
if ($count == 0)
$where .= "`Soortgerecht` = " . $soortgerecht . " ";
else
$where .= "AND `Soortgerecht` = " . $soortgerecht . " ";
++$count;
} elseif( !empty($moeilijkheid) ) {
if ($count == 0)
$where .= "`Moeilijkheid` = " . $moeilijkheid . " ";
else
$where .= "AND `Moeilijkheid` = " . $moeilijkheid . " ";
++$count;
} else {
$where = null; // if none of the conditions are met we null
// the entire `WHERE` statement so we can safely
// send to our SQL query regardless of no conditions
// being met
}
// then your sql statement could be something like:
$sql = "SELECT *
FROM tablename
$where"; // remember: if ($where == null)
// that means no filters are set and
// all records from table are returned
This example assumes that you want to handle your empty vars as null queries. It's a bit unclear in your question whether you want to skip querying for null values or if you want to set your null vars to default values. As mentioned in comments, setting vars to toggle on default values is really easy using a ternary operator.
Example 2 (setting a default value on empty vars):
$default_tijd = "whatever you want";
$tijd = ($tijd) ? $tijd : $default_tijd; // if $tijd is already set take
// that value, else use $default_tijd
However, I'm almost positive you don't want to return records for filters which aren't set to anything so setting a default value to your vars is just going filter records when you don't want to. What you probably want is the first example.
| |
doc_23535997
|
def f1(self, x):
return x
def f2(self, x):
return 2.0*x
def f3(self, x, function=f1):
return self.function(x)
then
>>>f0=f()
>>>f0.f3(1)
the error is:
"AttributeError: f instance has no attribute 'function'"
How can i fix it if i still wanna f3() to select a function of f1 or f2 in this class?
A: You can use .getattr():
class f:
def f1(self, x):
return x
def f2(self, x):
return 2.0 * x
def f3(self, x, function="f1"):
return getattr(self, function)(x)
Usage:
f0 = f()
print(f0.f3(1)) # prints 1
print(f0.f3(1, "f2")) # prints 2.0
| |
doc_23535998
|
Code:
for(int i=0;i<..........)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(ID,(((Node) node_list_variables.getDoc_id().item(0)).getNodeValue()));
map.put(ANSWER, (((Node) node_list_variables.getAnswer().item(0)).getNodeValue()));
map.put(QUESTION_ID, (((Node) node_list_variables.getQuestion_id().item(0)).getNodeValue()));
map.put(DESCRIPTION, i+1+", "+(((Node) node_list_variables.getQuestion().item(0)).getNodeValue()));
menuItems.add(map);
}
// Adding menuItems to ListView
// All filed data are not shown in the list KEY_ID is hidden
ListAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.certification_question_item,
new String[] { DESCRIPTION, QUESTION_ID, ANSWER, ID },
new int[] {R.id.questionText, R.id.question_id, R.id.answer });
setListAdapter(adapter);
R.id.answer is my radio buttonGroup Id
A: Why don't you just use an ArrayAdapter instead?
View layout = inflater.inflate(R.layout.whatever_you_called_your_layout_file, (ViewGroup)findViewById(R.id.whatever_you_called_your_layout_if_its_not_already_inflated));
ListView theList = (ListView)layout.findViewById(R.id.whatever_you_called_the_listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, android.R.id.text1, theNameOfTheStringArrayContainingYourValues);
theList.setAdapter(adapter);
theList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
theList.setItemChecked(checkedItem, true);
Just make sure you have set the int checkedItem to the value of the index in your String[] for the item you want checked.
| |
doc_23535999
|
URL We are using for request is
NSString *url = [NSString stringWithFormat:@"%@/payment-methods",baseURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request addValue:@"en_US" forHTTPHeaderField:@"Accept-Language"];
[request addValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:[NSString stringWithFormat:@"Bearer %@", delegate->AccessToken] forHTTPHeaderField:@"Authorization"];
[self performNetworkOperationWithRequest:request completionHandler:^(NSDictionary *requestDictionary, NSURLResponse *response, NSError *error) {
if(!error)
{
}
else
{
}}];
where baseURL = @"https://api.uber.com/v1.2";
And delegate->AccessToken= AccessToken we get at the time of Auth2.
NSHTTPURLResponse: 0x6080006374c0> { URL: https://api.uber.com/v1.2/payment-methods } { status code: 500, headers {
Connection = "keep-alive";
"Content-Length" = 75;
"Content-Type" = "application/json";
Date = "Mon, 02 Jan 2017 07:44:43 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=604800";
"X-Content-Type-Options" = nosniff;
"X-Uber-App" = "uberex-nonsandbox, migrator-uberex-optimus";
"X-XSS-Protection" = "1; mode=block";
} }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.