text:
Q: Image Classification using keras predict same output for different classes I have problem with my image classification model using keras.
This is the code which have binary class.
tried to set the number of images in datasets as equal.
this is a code for Keras model

train_data_dir = 'path'
validation_data_dir = 'path'
nb_train_samples = 2000
nb_validation_samples = 800
epochs = 10
batch_size = 16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.load_weights('second_try.h5')

and the model saved well.
so I run the test code
from keras.models import load_model
from keras.preprocessing import image
import numpy as np

# dimensions of our images
img_width, img_height = 150, 150

# load the model we saved
model = load_model('modelpath')
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

#predicting multiple images at once
img = image.load_img('imgpath', target_size=(img_width, img_height))

x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)

images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)
print(classes)

and both images from different classes are printed as 1.
Why does this happening?

A: You should be saving the model or model weights after your training, rather than doing load_weights after fit(). So, 2 ways to do this

*

*After model.fit(), do model.save_weights('second_try.hdf5') which only saves weights. To load the weights, you should first compile your model, and then call load_weights on the model as model.load_weights('second_try.hdf5')

*After model.fit(), do model.save('model.hdf5') which saves the weights and the model structure to a single HDF5 file. Then you can use that HDF5 file with load() to reconstruct the whole model, including weights.
model = load_model('model.hdf5')
Also, do check if your test data is being prepared correctly. As your training loop uses a generator to prepare the data, you should use a similar generator for preparing the test data as well.


text:
Q: Back button not made on navigation bar I started out with a navigation based project and am pushing further views onto the controller. The problem is that if I do not give a title to the navigation item then the back button is not drawn! Only if I give the navigation bar a title, will the back button come. It seems apple could'nt write "back" or "go back" in case of NO title. I do not want to give the navigation item a title(I'll use a label inside my view). So how do I fix this?
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"Home"; /// <- without setting the title, the back button won't show !
}

In the view didLoad method, if I remove the title, the back button won't show

A: Just create the back button yourself:
- (void)viewDidLoad
{
    [super viewDidLoad];

    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                             style:UIBarButtonItemStylePlain
                                                            target:nil
                                                            action:nil];
    [[self navigationItem] setBackBarButtonItem:back];
    [back release];
}

(If you prefer dot notation, self.navigationItem.backBarButtonItem = back;)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Github Shared as Link in visual studio Hi I have a git repository which is linked to my solution in visual studio
I have added some code to my solution that is outside of my repository as the code is shared across multiple solutions. I have added the code as add existing item add as Link.
How do I go about adding this code to git. It needs to be shared across multiple projects hence the reason for adding as a link.

A: If your using a setup that is basically 1 git repository per solution then I see 2 real options.  Unless you want to refactor things and make a separate solution for those shared components and then consume it as a nuget package.

*

*Include the shared code in an existing repository and force a specific directory structure for the checked out repositories.

Update : a bit more information This would force you to make a decision about where that shared code lives.  In your Team city configuration you would have to check out the repository with the shared code along with the solution you are trying to build.  It would force your build and development environments to maintain repositories side-by-side.

*Create a new repository for the shared components and add that repository as a git submodule.

Personally, I would go this route
Update : a bit more informationThis creates a parent to child relationship.  If the shared code is in a repository x when you checkout your solutions repo, the x repository will be inside of it and also checked out.  I don't really know much about team city, but I believe you can have it pull down the submodule's along with the repository. It shouldn't affect your CI environment.
Each comes with their own unique set of challenges.  Depending on your exact goals I can't really give anymore information.


text:
Q: the nuxt helper in define component How I can access to nuxt app into my define component setup function ?
I use nuxt2 with typescript. I want to access loading from the nuxt app like this :
$nuxt.$loading.start()

the answer in nuxt2 it is :
this.$nuxt

and the answer in nuxt3 it is :
const app = useNuxtApp()

but i no dont know what is the answer in nuxt 2 using typescript and composition api


text:
Q: Unable to expand my partition Im on gparted live with 50GB unallocated partition, but my linux partition can't be expanded.image

A: You're trying to expand partition 5. The free space is between Partition 3 and 4. So you'd have to move partition 4 to the left, then it should work.


text:
Q: How to execute a command for each of the sub folders? I have the following structure:
parent_folder
     |______subfolder1
     |           |________sub_subfolder_1
     |           |________sub_subfolder_2
     |           |________sub_subfolder_3
     |
     |______subfolder2
                 |________sub_subfolder_4
                 |________sub_subfolder_5
                 |________sub_subfolder_6

I need to be able to execute certain command on each of the sub_subfolder_x's
For my example I just try to echo the folders names.
this is what I tried but it doesn't work:
for /d %%x in (*) do (
cd %%x
for /d %%y in (*/%%x) do (
echo %%y
)
)

When I simply do
for /d %%x in (*) do (
echo %%x
)

it works and lists all the folders under the parent_folder. But my script that tries to cd to (*/%%x) doesn't work

A: Your main problem is */%%x. It should be %%x\*. You don't need to cd into that folder (and if you do, better use pushd, so you can easily revert it with popd)
@echo off
for /d %%x in (*) do (
  for /d %%y in ("%%x\*") do (
    echo %%y
  )
)

A: I found a way that also works for me:
@echo off

cd /d "%~dp0\parent_folder"

for /d %%x in (*) do (
     cd /d "%cd%\%%~x"
     for /d %%y in (*) do (
         echo current sub folder is %%y
        )
    )
pause

I just did some trial and errors until I made it work. I wonder if it is problematic from some reason and will not work in some cases?

A: You can retrieve the names of the sub folders by using dir with some switches and store them in an array (It's a bit of a trick because batch does not actually support arrays).
After that you can loop through this array.
Then you change directory to each of the folders in the array and execute the piece of code you want to execute in each of the sub folders.
Here is an example of that:
@echo off
setlocal enableDelayedExpansion

REM Retrieve Parent Folder
set parentfolder=%cd%

REM Retrieve Subfolders
set i=0
for /f "eol=: delims=" %%F in ('dir /b /ad *') do (
  set /a i+=1
  set "folder!i!=%%F"
)

REM Loop Through Sub Folders
for /l %%N in (1 1 %i%) do (
cd %parentfolder%\!folder%%N!
echo do something
)

A: @echo off && cd /d "%~dp0"

for /r /d %%i in (.) do pushd "%%~fi" && =;(
    %ComSpec% /v /r "echo\"!cd!"" & popd );=

Try using for /R /D, in one loop recursive in all subdirectories and run your command in each folder, being inside it:
 for /r /d %%i in (.) do pushd "%%~fi" && %ComSpec% /v /r "[Your Command Here]" & popd

*

*FOR /R - Loop through files (recursively)
FOR /D - Loop through several folders/directories

*The option /D /r is undocumented, but can be a useful combination,
while it will recurse through all subfolders the wildcard will only
match against Folder/Directory names (not filenames)
Note: Source linked to ss64.com

Obs.: If your command needs to make use of some "dependent" file that is in the looped folder ("%%~fi"), a pushd, command & popd will help you to execute the command in each folder correctly

*

*Some further reading:

*CMD /?

*Pushd /?

*

*Popd /?

*For Loop

*For /D Loop

*For /R Loop

*DelayedExpansion | %ComSpec% /v /r

A: @echo off
setlocal
set "curdir=%~dp0"
set "subdir=%curdir:~0,-1%\parent_folder"
for /f "usebackq tokens=*" %%d in (`dir /b /s /a:d "%subdir%"`) do echo %%d


text:
Q: ansible 2.3.1.0 install only from files I need to install ansible-2.3.1.0 only from files I copy to a firewalled host. The internally-supported pip install only grabs ansible 1.x, so I can't use that.
The default Python on the online host is 2.7.12, and the offline host 2.7.6.
Here's what I did
# on a separate host that can access the internet ...
ssh online_host
mkdir ~/ansible
cd ~/ansible

# download ansible and first-level requirements dependency tarballs
pip install --download . ansible
tar xvf ansible-2.3.1.0.tar.gz
pip install --download . -r ansible-2.3.1.0/requirements.txt

# this gave me these tarballs
ansible-2.3.1.0.tar.gz
Jinja2-2.9.6.tar.gz
paramiko-2.2.1.tar.gz
pycrypto-2.6.1.tar.gz
PyYAML-3.12.tar.gz

# install on the offline host
ssh offline_host
# the tarballs above were copied to here
cd ~/ansible
# unpack and offline install it
sudo pip install ansible-2.3.1.0.tar.gz --no-index --find-links file://`pwd`

But when I try to run ansible, it give me this:
ansible
Traceback (most recent call last):
  File "/usr/bin/ansible", line 25, in <module>
    from ansible.runner import Runner
ImportError: No module named runner

Has anyone actually installed ansible 2.3 like this? What am I missing?
I tried looking at deeper dependencies but I coulnd't figure out what this might be from (I see something about Ansible API changes from 1.x to 2.x, but I can't figure out from that what is up or what would fix this in my case.
EDIT:
After copying /usr/local/bin/ansible* over /usr/bin to rid myself of old 1.x leftover ansible command wrappers, the commands now start but when I run a playbook I get this (omitting playbook and ansible-playbook command-line since I don't think they matter):
TASK [Gathering Facts] *******************************************************************************************************
fatal: [slcmskafka-1169389.stratus.slc.ebay.com]:
FAILED! => {"changed": false, "failed": true, "msg":
"Unsupported parameters for (setup) module: gather_subset,gather_timeout.
Supported parameters include: fact_path,filter"}

A: Fixed.
I more thoroughly removed an older Ansible by this:
sudo pip uninstall ansible
# didn't need to autoremove
sudo apt-get remove ansible

then the /usr/local/bin/ansible* commands worked (and there were no longer any older /usr/bin/ansible* commands to replace) and my playbooks work too.


text:
Q: How to invoke a method in interface using reflection I have a class and that class 'class1' is implementing an interface interface1
I need to invoke a method in the class using the reflection.
I can't use the class name and interface name as it is because both the name will change dynamically.`
interface1 objClass = (interface1 )FacadeAdapterFactory.GetGeneralInstance("Class"+ version);
See the above code snippet. The class name and the interface name should change according to its version. I have created the instance for class by using
Activator.CreateInstance(Type.GetType("Class1"))

but i m not able to crete the same for interface
Is there any way to implement the above context.

A: You can't create instance of interface, just class that implements interface.
There are some ways to extract method (info) from interface.
ISample element = new Sample();

Type iType1 = typeof(ISample);
Type iType2 = element.GetType().GetInterfaces()
    .Single(e => e.Name == "ISample");
Type iType3 = Assembly.GetExecutingAssembly().GetTypes()
    .Single(e => e.Name == "ISample" && e.IsInterface == true);

MethodInfo method1 = iType1.GetMethod("SampleMethod");
MethodInfo method2 = iType2.GetMethod("SampleMethod");
MethodInfo method3 = iType3.GetMethod("SampleMethod");

method1.Invoke(element, null);
method2.Invoke(element, null);
method3.Invoke(element, null);

I hope it's sufficient.


text:
Q: How to call an overloaded function with boost::thread? class Foo
{
public:
    void method(int a,float b)
    {
        cout<<"This method takes float and int";
    }
    void method(char a,char b)
    {
        cout<<"This method takes two characters";
    }
 };

In a class with overloaded functions like the one above,creating a thread with boost::thread newThread(&Foo::method,foo_obj_ptr,a,b) throws the error " No overloaded function takes four arguments " . [ I have declared a and b as characters only.] My assumption is that with an overloaded function boost::thread is unable to bind correctly.Any solutions for this ?
I am using boost 1.54 with vs2010.

A: It doesn't have really much to do with boost, but rather with the compiler understanding which function you mean when you call an overloaded function (in a new thread or otherwise).
Here is your code + a solution using std::thread (no major difference):
#include <thread>
#include <iostream>

using namespace std;

class Foo
{
public:
    void method(int a,float b)
    {
        cout<<"This method takes float and int";
    }
    void method(char a,char b)
    {
        cout<<"This method takes two characters";
    }
 };

int main()
{
    Foo foo;
    typedef void (Foo::*fn)(char, char);
    thread bar((fn)(&Foo::method), &foo, 2, 3);
}

Note the
typedef void (Foo::*fn)(char, char);

which allows you to cast the first argument to thread:
thread bar((fn)(&Foo::method), &foo, 'b', 'c');

This cast tells the compiler which of the functions you mean.

A: Just use a lambda function taking two chars
int main()
{
    Foo foo;
    thread yay([&foo](char a, char b){ foo.method(a, b); }, 2, 3);
    yay.join();
}

Live Example.


text:
Q: Divergence of $ \frac{1}{s}\hat{s}$ in cylindrical coordinates In Griffiths' electrodynamics, the divergence of $\frac{1}{r^{2}}\hat{r}$  is evaluated in spherical coordinates to be $4\pi\delta(r)$. I encounter the same problem in case of $\frac{1}{s}\hat{s}$ where $s$ is the radius in cylindrical coordinates. I think that it is $2\pi\delta(s)$ but I  am not sure.
If I put this in the expression for divergence in cylindrical coordinates I get zero to be the answer but it is only intuitive that there should be some divergence at the origin as in the case of $\frac{1}{r^{2}}\hat{r}$.
If I compute the flux through a closed surface say a cylinder the flux through the top and bottom end is zero while flux through the lateral surface is $2\pi h$,where h is the height of cylinder .In this case it is dependent on the surface features(as opposed to the case of $\frac{1}{r^{2}}\hat{r}$).This violates the divergence theorem.What is the correct divergence of this vector field?
Could someone please help me with this problem?

A: So $1/s$ does not have a divergence. It cannot have a divergence. Divergences are a property of vector fields, it is a scalar field.
I think you may have meant $\vec F(s, \varphi, z) = \hat s / s = (x\hat x + y \hat y)/(x^2 + y^2)$, which has the nice property that it has zero divergence if $s\ne 0.$ If so, then I think this is an an answerable question.
But first I also have to correct a misconception (you may not have it but many students do): the divergence of $\hat r/r^2$ is not $4\pi \delta(r)$. It is, rather, $4\pi ~\delta_3\big(\vec r\big).$ This is a 3D Dirac $\delta$-function which looks for whether a volume includes the origin point $\vec 0$ in it, so we can write this in Cartesian coordinates as $\delta(x)~\delta(y)~\delta(z)$. This is distinct from the 1D Dirac $\delta$ function applied to the spherical coordinate $r$, $\delta(r).$ For one reason why this matters, it matters because we have a mathematical ambiguity about what $\int_0^X dx~\delta(x)$ should be, should it be 0 or 1 or maybe $1/2$ in between? The starting point of the integral is not clear on whether it contains that point at $x=0$ completely or halfway or not at all. And this is important here because all of our radial integrals start at 0 so if you choose $1/2$ as a nice intermediary then you would find that because the angular integral gives you $4\pi$ of solid angle already, the divergence of $\hat r / r^2$ is actually something like $2 \delta(r)$ when understood in that way. But it's just not a great way to understand the problem.
Now this misconception becomes important for us, because you are about to encounter a 2D Dirac $\delta$-function in 3D space and then it becomes very hard to denote what even we're talking about. To be clear, we are talking about a scalar field that in Cartesian coordinates would be $2\pi ~\delta(x)~\delta(y).$ You have the right prefactor. But as for how you would clearly denote that you want a 2D $\delta$ function within the 3D space, I am not sure... Possibly you could write $$\nabla\cdot \vec F = 2\pi~\int_{-\infty}^{\infty} dz_0~\delta_3\big(\vec r - z_0~\hat z\big),$$ using superposition to give a clear sense of "here is exactly what I mean." Because if you were to multiply that by some $f(\vec r)$ and then $\iiint d^3 r$ over some volume, that sort of expression should ultimately reduce it down to $\int_a^b dz_0~f(0, 0, z_0)$ as needed when all of the commutations are done. Or maybe we just invent the non-square matrix $$\mathbf P_z = \begin{bmatrix}1&0&0\\0&1&0\end{bmatrix}$$ and simply write $\nabla\cdot\vec F = 2\pi~\delta_2\big(\mathbf P_z~\vec r \big)$ for it, or so.
So if you are very careful about how you write $\delta_2$ then what you have said is correct, but if you are not very careful and you just write it as $\delta$ then people may misread you as talking about a 1D Dirac $\delta$ rather than a 2D Dirac $\delta$ and they would be very confused.


text:
Q: Why custom validator not called on touch event in Angular2? I have defined my custom Passwords validator like so:
  confirmPassword(group: AbstractControl): ValidationErrors | null {
    console.log('Validator invoked')

    if ( group.get('password_verify')?.pristine === false ||
         group.get('password_verify')?.touched === true ) {
      return group.get('password_verify')?.value !== group.get('password')?.value ? {
        passwords: "Passwords mismatch"
      } : null
    }
    return null
  }

And used it in a standart way for FormGroup:
  form: FormGroup = new FormGroup({
    phone: new FormControl('', Validators.required),
    email: new FormControl('', [Validators.required, Validators.email]),
    passwords: new FormGroup({
      password: new FormControl(''),
      password_verify: new FormControl('', this.myValidator)
    }, this.confirmPassword),
    first_name: new FormControl('', Validators.required),
    last_name: new FormControl('', Validators.required),
  });

Problem is that console.log only invoked after i type something to 'password_verify' input.
While standart Validators.required, f.x., invokes even if you just focus/unfocus input, without inputting anything.
How do i make my custom validator behave in the same way ?
You may notice this.myValidator another custom validator w/o implementation. I tried making factory function ValidatorFn that returns () => {} to validate input(thinking may be that's a correct way), but no luck - validator won't be called on touch event.
Angular v10

A: Try Angular Custom Validators
form: FormGroup = new FormGroup({
  phone: new FormControl('', Validators.required),
  email: new FormControl('', [Validators.required, Validators.email]),
  password: new FormControl(''),
  password_verify: new FormControl('')
  first_name: new FormControl('', Validators.required),
  last_name: new FormControl('', Validators.required),
}, { validators: confirmPassword });

export const confirmPassword: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
 const password = control.get('password').value;
 const confirmPassword = control.get('password_verify').value;

 return password === confirmPassword ? null : { password_mismatch: true }
}


text:
Q: Can a point of ramification be a regular value of a smooth map? I basically have this example in mind. Consider the unit circle $S^1$ as a submanifold of $\mathbb{R}^2$ (symmetric about the origin) and $[-1,1]$ as a submanifold of $\mathbb{R}$. Define the projection map $\pi: S^1 \to [-1,1], \pi(x,y) = x$ where $(x,y) \in S^1$. This map is smooth in the induced smooth structures and has constant rank 1 on $S^1$ (rank of $d\pi_{(x,y)}$ is 1). So by the inverse function theorem, every $x \in [-1,1]$ is a regular value and so there are open neighborhoods about $x$ and any point in its fiber that are diffeomorphic. But if $x = -1$ then there appears to be a problem because the open neighborhoods of $x$ are of the form $[-1,a), a\leq 1$ and $\pi$ is not injective on the preimage of any such open set.
So either I've made a mistake above or there can be issues at ramification points of the smooth map.

A: The projection map $\pi: \Bbb R^2\to\Bbb R$ defined by $(x,y)\mapsto x$ has indeed rank $1$, but this doesn't imply that the projection map $\pi: S^1\to \Bbb R$ (considered as a map between these manifolds) has rank $1$ at every point. Indeed, in $(\pm 1,0)$, it has rank zero.
If you parametrize a neighborhood of $(1,0)$ in $S^1$ by a parameter $\varphi\in (-\epsilon, \epsilon)$ and a map $\varphi\mapsto (\cos \varphi, \sin \varphi)$, then $\pi$ is represented (in this coordinate frame) by $\varphi\mapsto \cos \varphi$, which is a function with zero derivative for $\varphi=0$.


text:
Q: PDF File is not opening in Android Mobile PDF file is not showing

      <object data="Telugu Calendar 2016.pdf" type="application/pdf" width="500"       height="200">
         Brochure
      </object>

in android mobile i am writing coding  below
this same Exute in browser working fine but in android mobile pdf not showing  i am new one to phonegap Please Help me

A: As far as i know, Android don't support viewing PDFs out of the box in a WebView. You gotta use some cordova plugins like PDFViewer-Plugin or DocumentViewer-Plugin to achieve this in android mobiles.

A: Android provides PdfRenderer class (Added in API level 21).
You can try also to implement it using this.
I hope it will help you.


text:
Q: XSD element to to fetch Element Based on Starting and Ending Position 28169        199855888107336BAP05185    2850204722
38169        19985588810733600001BAP05185    2850204722

This is my file data and I want to create xsd schema that fetch value from 20 to 28 character number.

A: In BizTalk the following Flat Files schema would parse it, Field2 containing what you are after.
<?xml version="1.0" encoding="utf-16"?>
<xs:schema xmlns="http://Scratch2.SO72451573" xmlns:b="http://schemas.microsoft.com/BizTalk/2003" targetNamespace="http://Scratch2.SO72451573" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:annotation>
    <xs:appinfo>
      <b:schemaInfo standard="Flat File" root_reference="Root" default_pad_char=" " pad_char_type="char" count_positions_by_byte="false" parser_optimization="speed" lookahead_depth="3" suppress_empty_nodes="false" generate_empty_nodes="true" allow_early_termination="false" early_terminate_optional_fields="false" allow_message_breakup_of_infix_root="false" compile_parse_tables="false" />
      <schemaEditorExtension:schemaInfo namespaceAlias="b" extensionClass="Microsoft.BizTalk.FlatFileExtension.FlatFileExtension" standardName="Flat File" xmlns:schemaEditorExtension="http://schemas.microsoft.com/BizTalk/2003/SchemaEditorExtensions" />
    </xs:appinfo>
  </xs:annotation>
  <xs:element name="Root">
    <xs:annotation>
      <xs:appinfo>
        <b:recordInfo structure="delimited" preserve_delimiter_for_empty_data="true" suppress_trailing_delimiters="false" sequence_number="1" child_order="postfix" child_delimiter_type="hex" child_delimiter="0x0D 0x0A" />
      </xs:appinfo>
    </xs:annotation>
    <xs:complexType>
      <xs:sequence>
        <xs:annotation>
          <xs:appinfo>
            <b:groupInfo sequence_number="0" />
          </xs:appinfo>
        </xs:annotation>
        <xs:element maxOccurs="unbounded" name="Record">
          <xs:annotation>
            <xs:appinfo>
              <b:recordInfo sequence_number="1" structure="positional" preserve_delimiter_for_empty_data="true" suppress_trailing_delimiters="false" />
            </xs:appinfo>
          </xs:annotation>
          <xs:complexType>
            <xs:sequence>
              <xs:annotation>
                <xs:appinfo>
                  <b:groupInfo sequence_number="0" />
                </xs:appinfo>
              </xs:annotation>
              <xs:element name="Field1" type="xs:string">
                <xs:annotation>
                  <xs:appinfo>
                    <b:fieldInfo sequence_number="1" justification="left" pos_length="19" />
                  </xs:appinfo>
                </xs:annotation>
              </xs:element>
              <xs:element name="Field2" type="xs:string">
                <xs:annotation>
                  <xs:appinfo>
                    <b:fieldInfo sequence_number="2" justification="left" pos_length="9" />
                  </xs:appinfo>
                </xs:annotation>
              </xs:element>
              <xs:element maxOccurs="unbounded" name="Field" type="xs:string">
                <xs:annotation>
                  <xs:appinfo>
                    <b:fieldInfo sequence_number="3" justification="left" pos_length="1" />
                  </xs:appinfo>
                </xs:annotation>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Would parse it into the following XML
<Root xmlns="http://Scratch2.SO72451573">
    <Record xmlns="">
        <Field1>28169        199855</Field1>
        <Field2>888107336</Field2>
        <Field>B</Field>
        <Field>A</Field>
        <Field>P</Field>
        <Field>0</Field>
        <Field>5</Field>
        <Field>1</Field>
        <Field>8</Field>
        <Field>5</Field>
        <Field/>
        <Field/>
        <Field/>
        <Field/>
        <Field>2</Field>
        <Field>8</Field>
        <Field>5</Field>
        <Field>0</Field>
        <Field>2</Field>
        <Field>0</Field>
        <Field>4</Field>
        <Field>7</Field>
        <Field>2</Field>
        <Field>2</Field>
        <Field/>
    </Record>
    <Record xmlns="">
        <Field1>38169        199855</Field1>
        <Field2>888107336</Field2>
        <Field>0</Field>
        <Field>0</Field>
        <Field>0</Field>
        <Field>0</Field>
        <Field>1</Field>
        <Field>B</Field>
        <Field>A</Field>
        <Field>P</Field>
        <Field>0</Field>
        <Field>5</Field>
        <Field>1</Field>
        <Field>8</Field>
        <Field>5</Field>
        <Field/>
        <Field/>
        <Field/>
        <Field/>
        <Field>2</Field>
        <Field>8</Field>
        <Field>5</Field>
        <Field>0</Field>
        <Field>2</Field>
        <Field>0</Field>
        <Field>4</Field>
        <Field>7</Field>
        <Field>2</Field>
        <Field>2</Field>
    </Record>
</Root>


text:
Q: Updating acl file using JS in hyperledger-composer I am working on hyperledger playground. I have found that the access rules for participants can be specified manually on acl file in hyperledger composer. But is there a way that allows me to add rules to this file using JS?
Example:
There is an organization. It has some assets, and its number of employees is not fixed. As the admin adds new employees, their access rights on these assets is not known beforehand.
Is there a way such that as new employees are added, I can dynamically create rules for them, modifying the .acl file by script?

A: see the condition property in the reference doc https://hyperledger.github.io/composer/latest/reference/acl_language. As the condition property accepts code, you can invoke functions that exist within your business network .js files, however these functions are not allowed to invoke the composer runtime API. A summary of those functions not allowed can be found here
https://hyperledger.github.io/composer/latest/api/runtime-api
If you try to use them it will throw an error.


text:
Q: Open another ViewController without using a button? I am trying to open a ViewController2 from another ViewController1. I am not having any buttons, because the second ViewController should start after a sound has finished.
My function from ViewController1, that should call ViewController2:
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"audioPlayerDidFinishPlaying");

 //Here it should call the other ViewController

}

How can I handle this?

A: Try this... it's the same thing as doing it with a button:
 MyViewController* controller = [[MyViewController alloc] init];
 [self.navigationController pushViewController:controller animated:YES];

A: If you are using story board. Right click and drag from your source button to your destination view controller and then select push.
If you want to do it in code make sure you have a navigation viewcontroller then do as the answer suggested in regards to pushing the next view.


text:
Q: Force WordPress to always redirect to custom location after login, even if redirect_to is already set I have a server running WordPress 4.9.9 and PHP 7.2.
I am trying to redirect users after they log in.
To achieve this I am doing essentially this:
function admin_default_page() {
  return '/new-dashboard-url';
}

add_filter('login_redirect', 'admin_default_page');

It works great when you log in on this URL:
/wp-login.php
It does not work if redirect_to is already set in the query string:
/wp-login.php?redirect_to=some-place
I also tried the wp_login hook just in case but that doesn't even fire if redirect_to is set in the query string.
add_action('wp_login', 'admin_default_page');

How can I get WordPress to always redirect to /new-dashboard-url after login, regardless of what may or may not be set in the query string.
At the moment I am hacking my way around it by redirecting the login page to self if redirect_to is set in the query string to strip it out, but to my mind that's just that - a hack.
I can't help but think that both login_redirect and wp_login worked regardless of redirect_to being set.
Did the behaviour of these hooks change recently or am I just doing it wrong?


text:
Q: How to crawl the whole website, if data append with Javascript after scrolling I need to crawl a website, but the problem is, there is no linked pagination at the bottom. Data appends if you scroll to the bottom. Now how can I make this happen with my crawler? Are there any ideas?

A: Try examining the script that executes to append the data when you scroll down.  It must retrieve the additional data somehow -- just see what it's doing, and have your crawler do the same thing.

A: Using a robot like Selenium could work, you can simulate a real user in a real navigator. One thing I did with facebook once was to use a JavaScript interpreter in C++/Qt and then send request via it. A lot faster than Selenium.
I'm sure Google has a lot more processing power than you do, and webmaster do everything they can to be parsed by them.


text:
Q: Unable to change image when clicking on button using CSS I am developing web controlled Home Automation using Raspberry Pi. I referred the following the link
https://circuitdigest.com/microcontroller-projects/iot-raspberry-pi-home-automation
But I am customizing HTML, CSS page. I have developed HTML page as follows

Web Based Controlled Home Automation using Raspberry Pi

I write script (.js ) and stylesheet for same (.css)
My .js file as follows
webiopi().ready(function() {
            webiopi().setFunction(4,"out");
            //webiopi().setFunction(18,"out");
            //webiopi().setFunction(22,"out");
            //webiopi().setFunction(23,"out");

            var content, button;
            content = $("#content");

            button = webiopi().createGPIOButton(4,"Room 1");
            content.append(button);

        /* $('content').click(function(){
                         $('#pic1').attr('src','/img/roomlightoff.png');
        });
        */

My css file is as follows
button {
                    display: block;
                    position: absolute;
                    margin: 40px 610px;
                    padding: 0 10px;
                    text-align: center;
                    text-decoration: none;
                    width: 130px;
                    height: 40px;
                    font: bold 18px/25px Arial, sans-serif;
                    color: black;

                text-shadow: 1px 1px 1px rgba(255,255,255, .22);
                -webkit-border-radius: 30px;
                -moz-border-radius: 30px;
                border-radius: 30px;

                -webkit-box-shadow: 1px 1px 1px rgba(0,0,0, .29), inset 1px 1px 1px rgba(255,255,255, .44);
                -moz-box-shadow: 1px 1px 1px rgba(0,0,0, .29), inset 1px 1px 1px rgba(255,255,255, .44);
                box-shadow: 1px 1px 1px rgba(0,0,0, .29), inset 1px 1px 1px rgba(255,255,255, .44);

                -webkit-transition: all 0.15s ease;
                -moz-transition: all 0.15s ease;
                -o-transition: all 0.15s ease;
                -ms-transition: all 0.15s ease;
                transition: all 0.15s ease;
        }

#gpio4.LOW {
                    background-color: Gray;
                    color: Black;
                    // background-image:url('/img/roomlightoff.png');
            }

            #gpio4.HIGH {
                    background-color: Red;
                    color: LightGray;
            }

it's working fine. Currently, when I clicked on button (#gpio.HIGH / # gpio.LOW) background color changes accordingly. But the problem is that I also want to change image source simultaneously. When I click the button, I want to change background-image source at the same time. Right now, the page displays a constant image.
I tried background-image:url('/img/roomlightoff.png');
but its not working , it changes background-image of button,not page.
please help to solve this.


text:
Q: Extract the contents from ul tag in to an excel file I have this web site and I want to extract the following:
http://www.ipmart.com.my/main/product/BlackBerry_Porsche_Design_P_9982_Silver_BlackBerry_Warranty_454805.php?prod=454805
image from the website, the heading, the decription and the specification and the package content.
I tired the following lines but it extracts the wrong info
TAG POS=1 TYPE=A ATTR=div:productDetailUl EXTRACT=TXT
TAG POS=1 TYPE=H1 ATTR=TXT:* EXTRACT=TXT
Can anyone help me out with this?
Thank you.
Nuwan.

A: I would try using XPATH to extract the correct information.
It's easiest to grab the xpath with Chrome:

*

*Right click on what you want to extract

*Click "inspect element"

*Right click on the highlighted line of code within the inspection
tool (you may have to adjust this, but you basically want to grab
the element closest to what information you're trying to extract.
It's usually pretty good, but may take a little work.)

*Click "Copy Xpath"

Within your iMacros script, use:
TAG XPATH="paste your xpath between these quotes" EXTRACT=TXT
I would use iMacros for Firefox for this, as it seems to bug out a little less.


text:
Q: Colocar un formulario siempre al fondo C# Mi situación a resolver es la siguiente.
Tengo un formulario "HOME" que es el form principal, a su vez tengo el formulario "B" (vamos a llamarlo así).
Pongamos nos en la situación donde ambos formularios están minimizados. Al maximizar el form "B" quisiera que se maximice también el "HOME" al fondo.
También que al seleccionar el Home, se maximicen todas las ventanas abiertas para que quede "HOME" de fondo.
Les dejo una imagen por si aclara un poco más.

A: Podrias integrar ambos formularios usando MDI entonces el form home sera el contenedor del form B
Para esto debes hacer que el home tenga la propiedad IsMdiContainer en true
Y el form B cuando lo inicias asignas
FormB frm = new FormB();
frm.MdiParent = this;
frm.Show();

En este caso this seria la instancia del form home
De esta forma un form estara contenido y al minimizar el home tambien los haran los forms que este contenga


text:
Q: Create a new array with common string in all arrays in ruby Lets say we have below array
arrays=[["a","b", "c"],["b","g","c"],["b","c","g"]]

To find common array fields we can do arrays[0] & arrays[1] & arrays[2] which will return ["b","c"] in this case.  This works fine. But how can we do the same when the array count is not predictable?
My initial thought is doing something like a loop like this.
array_count.times do |index|
 #but this way how can I achieve same above or any better approach???
end

Thank you.

A: Use Reduce method
result=arrays.reduce do |x,y|
  x & y
end

p result

output
["b", "c"]

Update
Another short way would be
 arrays.reduce(:&)


text:
Q: I can't get this ajax call to work, no json output I have the code below in my html. I can't get alert to send me back anything.
    $.ajax({
    url:"proxy.php?url=http%3A%2F%2Fapi.rottentomatoes.com%2Fapi%2Fpublic%2Fv1.0%2Flists%2Fmovies%2Fupcoming.json%3Fpage_limit%3D16%26page%3D1%26country%3Dus%26apikey%3Dk4uaze4937mw3hf82upstxqw%0A",
    type:'GET',
    dataType:"json",
    success:function(data){var title1 = data.movies[1].title; alert (title1);}
});

here is my proxy.php file.
<?php
    // File Name: proxy.php
    if (!isset($_GET['url'])) die();
    $url = urldecode($_GET['url']);
    $url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file system
    echo file_get_contents($url);

I am using proxy because the server I am trying to connect to does not have jsonp.
This is the api I am calling, and the json
http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?page_limit=16&page=1&country=us&apikey=k4uaze4937mw3hf82upstxqw

A: Now works. JSONP is ok, you can use it without your PHP.
<script type="text/javascript">

        $( document ).ready(function() {

            $.ajax({

                url:'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?page_limit=16&page=1&country=us&apikey=k4uaze4937mw3hf82upstxqw',
                type:'GET',
                dataType:'jsonp',

                success:function(data){

                    alert(data);

                    var title1 = data.movies[1].title;
                    alert(title1);

                },

                error: function(xhr, textStatus, errorThrown){
                    alert(xhr);
                    alert(textStatus);
                    alert(errorThrown);
                }

            });

        });

    </script>


text:
Q: form in a many to many relationship Im starting with rails.
Im trying to implement a has_many_belongs_to_many relationship between two models, project and users, I did with a simple join table as well. But I can´t do that work. Im getting crazy with this. I would appreciate if anybody can help.
I try this solution but its giving me a mistake
Rails : assign multiple params via form_for check_box for HABTM relationship
Controler:
 def create
 @users = User.find params[:project].delete[:users]
 @project = Project.new(params[:project])
 @project.users = @users

.....
def project_params
  params.require(:project).permit(:client_id, :pstate_id, :name,
  :description,  :start_date, :deadline, :is_closed, :workload, :users_ids => [])
  end

My view is:

 <%= f.label :user_ids, "Users" %>

 <%= f.collection_select :user_ids, User.order(:name), :id, :name, {},
 {multiple: true}    %>

And now I get this mistake:
ArgumentError in ProjectsController#create
wrong number of arguments (0 for 1)
Extracted source (around line #37):

35
36
37
38
39
40

authorize! :create, @project
#@project = Project.new(project_params)
@users = User.find params[:project].delete[:users]
@project = Project.new(params[:project])
@project.users = @users
#@users = @user.projects

Rails.root: C:/Ruby200/onlineproyect
Application Trace | Framework Trace | Full Trace

app/controllers/projects_controller.rb:37:in `create'

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"wU9MgWv40XMqoy0sDZXd5vtqpFGxXHPmLNm/BmrvVZY=",
 "project"=>{"client"=>"1",
 "pstate"=>"1",
 "name"=>"Projecto 1",
 "description"=>"el ultimo",
 "start_date(1i)"=>"2014",
 "start_date(2i)"=>"11",
 "start_date(3i)"=>"27",
 "deadline(1i)"=>"2014",
 "deadline(2i)"=>"11",
 "deadline(3i)"=>"27",
 "workload"=>"",
 "user_ids"=>["",
 "1",
 "2"]},
"commit"=>"Create Project"}

-I have tried many different things....
Thanks

A: Try changing it to:
@users = User.find params[:project].delete[:user_ids]


text:
Q: Using date comparison in LINQ when querying SharePoint OData service ANSWERED: Go below to find my answer to this question.
I am trying to consume SharePoint 2010 OData from an ASP.NET MVC 3 project using LINQ. I created a default project using the ASP.NET MVC 3 project template with the Razor view engine (VS 2010). I added a service reference pointing to my SharePoint 2010 site.
In my HomeController's Index method (this is just a test project), I created a variable to hold the context and set the Credentials property of the context variable to the current default credentials.
A link query like the following works fine and I can use the created variable to access any of the data:
var query = from a in context.Alerts
            select a;

This query simply gets all of the announcements from a list called Alerts in the SharePoint site. This list has fields for the Title, Content, Beginning Date, and Expiration Date.
When I change the query to the following, I do not get the expected results:
var query = from a in context.Alerts
            where (a.Begins < DateTime.Now)
            select a;

This query ignores the time component of the date. For example, if a.Begins contains a datetime from yesterday, the query returns the AlertItem. If on the other hand, a.Begins contains a datetime with the current date (but an earlier time) the comparison returns false (and a.Begins == DateTime.Now returns true).
If I do the following, the second LINQ query works as expected:
var query = (from a in context.Alerts
            select a).ToList();
var query2 = from q in query
             where (q.Begins < DateTime.Now)
             select q;

What am I missing?

A: For a Linq to SharePoint query that needs to include the time element of the DateTime you can use TimeOfDay.
var next_slots = (from s in dc.HRDates
                  where
                  s.StartTime.HasValue &&
                  s.StartTime.Value.Date == appt.Value.Date &&
                  s.StartTime.Value.TimeOfDay == appt.Value.TimeOfDay
                  ...

A: I have not used SharePoint 2010's OData. However, when querying against the SharePoint 2010 object model, the anomaly you posted is a common behavior, re: you must convert the query to a list before you can query the data.
The typical pattern here is to:
var query = someSharePointQuery.ToList();

var results = query.Where(...).First(...);

Seems odd, but this is how SP 2010 seems to work.

A: Is DateTime.Today getting used in there somewhere? I did some prototyping with LinqPad, and the only way to duplicate your results was if I had the query using "where (a.Begins < DateTime.Today)"
Here's the quick sketch I did of what it sounds like you're describing:
void Main()
{
    List<Alerts> alerts = new List<Alerts>();
    alerts.Add(new Alerts(DateTime.Now.AddDays(-1)));
    alerts.Add(new Alerts(DateTime.Now));

    var query = from a in alerts
                where (a.Begins < DateTime.Now)
                select a;
    foreach (var element in query)
    {
        Console.WriteLine(element.Begins);
    }

}
public class Alerts
{
    public DateTime Begins {get; set;}
    public Alerts(DateTime begins)
    {
        Begins = begins;
    }
}

As I mentioned, the only way to duplicate your described results was if I changed DateTime.Now to DateTime.Today in the where clause. I would look through your code for accidental usages of the wrong DateTime method.
As an aside, I HIGHLY recommend using LinqPad for prototyping your Linq queries... It can save you time by allowing you to quickly iterate over your code and figure out what your trouble spots are. Also, it's very much worth the $50 for intellisense and other premium features.

A: After piecing together information from a lot of different sources -- none of which dealt with the exact circumstances of the problem that I am having, I've come to the following conclusion:
When querying SharePoint data using the SharePoint Object Model and Collaborative Application Markup Language (CAML), SharePoint by default does not use the time component of DateTime elements when doing comparisons. To tell SharePoint to use the time component, you must include the IncludeTimeValue = 'TRUE' property on the value type as shown here:
<Where>
 <Eq>
  <FieldRef Name='Begins' />
  <Value Type='DateTime'  IncludeTimeValue='TRUE'>
   2008-03-24T12:00:00Z
  </Value>
 </Eq>
</Where>

I found several blog posts that referenced a bug in LINQ to SharePoint that caused the generated CAML to be output as:
<Where>
 <Eq>
  <FieldRef Name='dateTimeField'  IncludeTimeValue='TRUE' />
  <Value Type='DateTime'>
   2008-03-24T12:00:00Z
  </Value>
 </Eq>
</Where>

Notice that the IncludeTimeValue = 'TRUE' is on the FieldRef element instead of the Value element. Since this is not the right place for that property, it causes all LINQ to SharePoint queries that perform datetime comparisons to only compare on the date component.
Since I am seeing that exact same behavior when using LINQ and WCF Data Services to connect to SharePoint, I can only assume that under the covers LINQ/WCF Data Services is producing the same invalid CAML.
The solution (assuming I still want to use LINQ/WCF Data Services) is to perform two queries (as stated in the original question). The first LINQ query pulls the list data from SharePoint and stores it in a List. The second LINQ query handles the date comparisons to only pull the data I want.
Since in my particular circumstance, I may have many entries in the SharePoint list covering a large time span but will only be interested in entries on a particular day or couple of days, I wanted to find a way not to bring back the entire list in the first query.
What I settled on was doing a <= and >= comparison to get close, and then further limiting that in my second query. So my two queries now become:
DateTime RightNow = DateTime.Now;
var query = (from a in context.Alerts
             where (a.Begins <= RightNow) && (a.Expires >= RightNow)
             select a).ToList();
var query2 = from q in query
             where q.Begins < RightNow) && (a.Expires > RightNow)
             select q;

The first LINQ statement will return all the items that I am ultimately interested in; along with a few that I'm not (because it's comparing just the date component of the datetime). The second LINQ statement will further pare that down to just those that I'm interested in.

A: I can confirm the bug with SharePoint 2010 LINQ to SharePoint not creating the correct CAML (adding IncludeTimeValue='True' to the FieldRef instead of the Value) is fixed by the October 2013 Cumulative Update to SharePoint Foundation 2010. The hotfix can be downloaded from http://technet.microsoft.com/en-us/sharepoint/ff800847.aspx.
The same bug exists also in SharePoint 2013 which I was informed by Microsoft support should be fixed in the December 2013 Cumulative Update to SharePoint Foundation 2013, but I cannot confirm this. I was informed that the fix is also deployed to Office 365, but I cannot confirm this.


text:
Q: Solving equation of motion for velocity Assume we have a skateboarder in an halfpipe with radius R.

The equation of motion is: $\ddot{x}=-g\frac{x}{R}\sqrt{1-(\frac{x}{R})^2}$
Now, I want to find v(x) for the skateboarder, if we drag him up to a height $h_0$ and let him skate from there. We also now that $U(\phi)=mgR(1-\cos(\phi))$
I had two idea. First one was using conversation of energie, like: $U=E_{kin}+E_{pot}$ and then solve for $v$. (That's what the solution does, so it would be okay)
The other idea was: $v(x)=\dot{x}=\int_0^{x_0} \ddot{x}$.
Is there a reason, that this approach, integration the eq. of motion, wouldn't work?

A: The conservation of Energy is the most easy feature you may use.
For what concerns the integral, what you'd get would be:
$$\int -g \frac{x}{R}\sqrt{1 - \frac{x^2}{r^2}}\ \text{d}x = -\frac{g}{R}\left(-\frac{1}{3} r^2 \left(1-\frac{x^2}{r^2}\right)^{3/2}\right)$$
That is
$$\frac{gr^2}{3R} \left(1-\frac{x^2}{r^2}\right)^{3/2}$$
What do you think?


text:
Q: Keycloak Java admin client returns 400 Error on triggering verification email I am using keycloak server version 8.0.1 and keycloak java admin client version 8.0.1 on spring boot 2.2, (with webflux and netty instead of tomcat, if that sort of info helps).
After creating a user, when I try sending the verification email using "executeActionsEmail" method provided by the admin client, I get
javax.ws.rs.BadRequestException: HTTP 400 Bad Request
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.handleErrorStatus(ClientInvocation.java:219) ~[resteasy-client-3.9.1.Final.jar:3.9.1.Final]

My Code
//Keycloak Admin Client Bean
 @Bean
    public Keycloak keycloak(){
        return KeycloakBuilder.builder()
                .serverUrl(keycloakConfigs.getAUTH_SERVER_URL())
                .realm(keycloakConfigs.getREALM())
                .grantType(OAuth2Constants.CLIENT_CREDENTIALS)
                .clientId(keycloakConfigs.getCLIENT_ID())
                .clientSecret(keycloakConfigs.getCLIENT_SECRET()).build();
    }

//Method Triggering email ('id' variable refers to successfully created user Id (UUID , not username or email ) in keycloak)

 @Override
    public void sendVerificationEmail(String id){
        log.debug("Sending email verification for id {}",id);
            List<String> actions=Arrays.asList(keycloakConfigs.getEMAIL_ACTIONS().split(","));
            keycloakAdminClient
                    .realm(keycloakConfigs.getREALM())
                    .users()
                    .get(id)
                    .executeActionsEmail(keycloakConfigs.getCLIENT_ID()
                            ,keycloakConfigs.getEMAIL_REDIRECT_URI(),actions);
    }

**Dependencies on my pom file ** [Just the relevant part, not entire structured pom ofc]
<properties>
        <java.version>1.8</java.version>

        <keycloak.version>8.0.1</keycloak.version>
        <resteasy.version>3.9.1.Final</resteasy.version>
    </properties>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <artifactId>keycloak-admin-client</artifactId>
            <groupId>org.keycloak</groupId>
            <version>${keycloak.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
            <version>${resteasy.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson2-provider</artifactId>
            <version>${resteasy.version}</version>
        </dependency>

FULL STACK TRACE
javax.ws.rs.BadRequestException: HTTP 400 Bad Request
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.handleErrorStatus(ClientInvocation.java:219)
    at org.jboss.resteasy.client.jaxrs.internal.proxy.extractors.DefaultEntityExtractorFactory$3.extractEntity(DefaultEntityExtractorFactory.java:50)
    at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:151)
    at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
    at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
    at com.sun.proxy.$Proxy124.executeActionsEmail(Unknown Source)
    at com.mycompany.profile.service.impl.KeycloakIdentityImpl.sendVerificationEmail(KeycloakIdentityImpl.java:43)
    at com.mycompany.profile.web.ProfileController.post(ProfileController.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.reactive.result.method.InvocableHandlerMethod.lambda$invoke$0(InvocableHandlerMethod.java:147)
    at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:118)
    at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1705)
    at reactor.core.publisher.MonoZip$ZipCoordinator.signal(MonoZip.java:247)
    at reactor.core.publisher.MonoZip$ZipInner.onNext(MonoZip.java:329)
    at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:173)
    at reactor.core.publisher.FluxDefaultIfEmpty$DefaultIfEmptySubscriber.onNext(FluxDefaultIfEmpty.java:92)
    at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FluxSwitchIfEmpty.java:67)
    at reactor.core.publisher.Operators$ScalarSubscription.request(Operators.java:2267)
    at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.set(Operators.java:2075)
    at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onSubscribe(Operators.java:1949)
    at reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:191)
    at reactor.core.publisher.MonoFlatMap.subscribeOrReturn(MonoFlatMap.java:53)
    at reactor.core.publisher.Mono.subscribe(Mono.java:4095)
    at reactor.core.publisher.MonoZip.subscribe(MonoZip.java:128)
    at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:55)
    at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.drain(MonoIgnoreThen.java:153)
    at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:56)
    at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:55)
    at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:150)
    at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FluxSwitchIfEmpty.java:67)
    at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:76)
    at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.innerNext(FluxConcatMap.java:274)
    at reactor.core.publisher.FluxConcatMap$ConcatMapInner.onNext(FluxConcatMap.java:851)
    at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:121)
    at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:173)
    at reactor.core.publisher.Operators$ScalarSubscription.request(Operators.java:2267)
    at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.request(MonoPeekTerminal.java:132)
    at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.request(FluxMapFuseable.java:162)
    at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.set(Operators.java:2075)
    at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onSubscribe(Operators.java:1949)
    at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onSubscribe(FluxMapFuseable.java:90)
    at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onSubscribe(MonoPeekTerminal.java:145)
    at reactor.core.publisher.MonoJust.subscribe(MonoJust.java:54)
    at reactor.core.publisher.Mono.subscribe(Mono.java:4110)
    at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:441)
    at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onSubscribe(FluxConcatMap.java:211)
    at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:161)
    at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:86)
    at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:55)
    at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52)
    at reactor.core.publisher.Mono.subscribe(Mono.java:4110)
    at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.drain(MonoIgnoreThen.java:172)
    at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:56)
    at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:55)
    at reactor.netty.http.server.HttpServerHandle.onStateChange(HttpServerHandle.java:64)
    at reactor.netty.tcp.TcpServerBind$ChildObserver.onStateChange(TcpServerBind.java:228)
    at reactor.netty.http.server.HttpServerOperations.onInboundNext(HttpServerOperations.java:465)
    at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:90)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:377)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:355)
    at reactor.netty.http.server.HttpTrafficHandler.channelRead(HttpTrafficHandler.java:170)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:377)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:355)
    at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436)
    at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:321)
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:295)
    at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:377)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:355)
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:377)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:714)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:650)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:576)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.lang.Thread.run(Thread.java:748)

Any help would be very helpful!


text:
Q: Marketo API Custom Data I am using the Marketo API V1 to get lead data from a customers Marketo account. I have successfully connected to the API (by going through their documentation).
I can get data for a single lead however it only displays the default data (id, firstName, lastName, email) and I know there are a lot of custom data fields (company, salutation, jobTitle etc.) but this does not show from the API - do you know how I can access this custom data?
Below is the API URL I am using which works fine just not showing all the data I require:
https://<<url>>/rest/v1/leads.json?access_token=<<token>>&filterType=email&filterValues=oliver@test.com

This returns:
{"requestId":"1261b#14f40fc3156","result":[{"id":2755951,"updatedAt":"2015-08-18T10:58:42Z","lastName":"wells","email":"oliver@test.com","createdAt":"2015-06-02T09:36:48Z","firstName":"oliver"}],"success":true}

Thank you very much!

A: You need to include a parameter, 'fields', which has a comma-separated list of field names to retrieve a given set of fields: http://developers.marketo.com/documentation/rest/get-multiple-leads-by-filter-type/  See example 2, there.


text:
Q: yii: retrieve just the form name class when using namespaces I have a code similar to this to handle a form submission:
use \my-project\web\models\forms\RegisterOrganizationForm;
...
var_dump($_POST);die();
$model=new LoginForm;
if(isset($_POST['LoginForm']))
    $model->attributes=$_POST['LoginForm'];

The output of that var_dump is (well, just the part regarding the values of the form):

["\my-project\web\models\forms\LoginForm"]=> array(1) {...

As you can see the namespace has been added (I didn't expect this..), so, how can I get just something like this below when vardumping??:
["LoginForm"]=> array(1) {...

Javier

A: First you are calling die() before you set the model attributes to the data received by the form.
Second you are doing a var_dump of $_POST instead do var_dump $_POST['LoginForm']
Third why do you want to do a var_dump if you want to see what is being sent back from the form use a tool like firebug for FireFox or developer tools in chrome

A: I had the same issue as you.
Patch the following file:
/path/to/yii/framework/web/helpers/CHtml.php
Find the method 'resolveName', replace it with the following:
/**
 * Resolves a class name, removing namespaces.
 */
public static function resolveClassName($model){
    return end(explode('\\',get_class($model)));
}

/**
 * Generates input name for a model attribute.
 * Note, the attribute name may be modified after calling this method if the name
 * contains square brackets (mainly used in tabular input) before the real attribute name.
 * @param CModel $model the data model
 * @param string $attribute the attribute
 * @return string the input name
 */
public static function resolveName($model,&$attribute)
{
    if(($pos=strpos($attribute,'['))!==false)
    {
        if($pos!==0)  // e.g. name[a][b]
            return self::resolveClassName($model).'['.substr($attribute,0,$pos).']'.substr($attribute,$pos);
        if(($pos=strrpos($attribute,']'))!==false && $pos!==strlen($attribute)-1)  // e.g. [a][b]name
        {
            $sub=substr($attribute,0,$pos+1);
            $attribute=substr($attribute,$pos+1);
            return self::resolveClassName($model).$sub.'['.$attribute.']';
        }
        if(preg_match('/\](\w+\[.*)$/',$attribute,$matches))
        {
            $name=self::resolveClassName($model).'['.str_replace(']','][',trim(strtr($attribute,array(']['=>']','['=>']')),']')).']';
            $attribute=$matches[1];
            return $name;
        }
    }
    return self::resolveClassName($model).'['.$attribute.']';
}

Hope this helps!
P.S. For anyone who thinks this is silly or unnecessary, client side validators don't work because you can't select an element by ID with backslashes using JavaScript (or at least with jQuery)


text:
Q: incorporating an if statement to set value limits I am creating a battleship program for my program; the program works fine but im trying to make sure when the user puts a coordinate out of range the program will say the coordinate they've inputted is incorrect. this is the code:
    #include <stdio.h>
    #include <stdlib.h>

    void startBoard(int board[][5])
{
  int line, column;
    for(line=0 ; line < 5 ; line++ )
        for(column=0 ; column < 5 ; column++ )
            board[line][column]=-1;
 }

void showBoard(int board[][5])
{

int line, column;

    printf("\t1 \t2 \t3 \t4 \t5");
    printf("\n");

    for(line=0 ; line < 5 ; line++ ){
        printf("%d",line+1);
        for(column=0 ; column < 5 ; column++ ){
            if(board[line][column]==-1){
                printf("\t~");
            }else if(board[line][column]==0){
                printf("\t*");
            }else if(board[line][column]==1){
                printf("\tX");
            }

        }
        printf("\n");
    }

}

void startShips(int ships[][2]){
    srand(time(NULL));
    int ship, last;

    for(ship=0 ; ship < 3 ; ship++){
        ships[ship][0]= rand()%5;
        ships[ship][1]= rand()%5;
for(last=0 ; last < ship ; last++){
            if( (ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]) )
                do{
                    ships[ship][0]= rand()%5;
                    ships[ship][1]= rand()%5;
                }while( (ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]) );
        }

    }
}

void giveShot(int shot[2])
{

    printf("Line: ");
    scanf("%d",&shot[0]);
    shot[0]--;

    printf("Column: ");
    scanf("%d",&shot[1]);
    shot[1]--;

}

int hitship(int shot[2], int ships[][2])
{
    int ship;

    for(ship=0 ; ship < 3 ; ship++){
        if( shot[0]==ships[ship][0] && shot[1]==ships[ship][1]){
            printf("You hit a ship with the shot (%d,%d)\n",shot[0]+1,shot[1]+1);
            return 1;
        }
    }
    return 0;
}

void tip(int shot[2], int ships[][2], int attempt)
{
    int line=0,
        column=0,
        row;

    //count how many ships there is line/column
    for(row=0 ; row < 3 ; row++){
        if(ships[row][0]==shot[0])
            line++;
        if(ships[row][1]==shot[1])
            column++;
    }

    printf("\nDica %d: \nline %d -> %d ships\ncolumn %d -> %d ships\n",attempt,shot[0]+1,line,shot[1]+1,column);
 }

 void changeBoard(int shot[2], int ships[][2], int board[][5]){
    if(hitship(shot,ships))
        board[shot[0]][shot[1]]=1;
    else
        board[shot[0]][shot[1]]=0;
}

int main() {
    int board[5][5];
    int ships[3][2];
    int shot[2];
    int attempts=0,
        hits=0;

    startBoard(board);
    startShips(ships);

    printf("\n");

    do{
        showBoard(board);
        giveShot(shot);
        attempts++;

        if(hitship(shot,ships)){
            tip(shot,ships,attempts);
            hits++;
        }
        else
            tip(shot,ships,attempts);

        changeBoard(shot,ships,board);

    }while(hits!=3);

    printf("\n\n\nFinished game. You hit the three ships in %d attempts", attempts);
    showBoard(board);
}

A: I think a while statement would be more useful than if.
First ask the user to enter the value. Then while the user enters incorrect values you keep asking him again.
It could look like this:
printf("Line: ");
scanf("%d",&shot[0]);
while(shot[0]<lower_bound || shot[0]>upper_bound){
    printf("Incorrect entry");
    printf("Enter a correct Line: ");
    scanf("%d",&shot[0]);
}
shot[0]--;

If you really need the if you could change the while with the if, but that would only check the value once whereas a while statement keeps checking until you get what you need.


text:
Q: Search by Attachment ID I'm building a stock photo page for my company where we upload all photos our staff created so that it can be used later. It shows the ID of the image by post->ID so that users can see it, note it and be useful later - just like any other stock photo website.
However, when I try to use the ID and searching it in the search field, nothing comes out. I'm using Search Everything plugin but it doesn't seem to do anything. All other search by ID plugins only work on posts, not attachments (images).
So is there any plugins out there that I can use or do I need to add a script in my functions.php?

A: The WP_Query class can match IDs as well as search terms. An idea would be to use the pre_get_posts action to detect if the search term is numeric and, if it is, set the query to work with attachments while passing the search as the ID.
function wpse223307_allow_search_by_attachment_id( $query ) {

    //Only alter the query if we are in a search screen,...
    if( ! is_search() ) :
        return;
    endif;

    //...the search term has been set...
    if( ! isset( $query->query_vars['s'] ) ) :
        return;
    endif;

    $search_term = $query->query_vars['s'];

    //...and the search term is a number
    if( ! is_numeric( $search_term ) ) :
        return;
    endif;

    //Set the post type and post status to work with attachments (assuming you want to exclude other post types in numeric searches)
    $query->set( 'post_type', array( 'attachment' ) );
    $query->set( 'post_status', array( 'inherit' ) );

    //Match the search term with the attachment's ID and remove it from the query
    $query->set( 'p', $search_term );
    $query->set( 's', '' );

}

add_action( 'pre_get_posts', 'wpse223307_allow_search_by_attachment_id');


text:
Q: "Error: No such file or directory" for input that has to be generated first I have two rules for STAR, STAR_genome does some indexing for the STAR rule, therefore the input of STAR is the direct output from STAR_genome - so far so simple. But when I try to run this, the STAR_genome rule is ignored (not listed in job count) and I get the following exception:

FileNotFoundError: [Errno 2] No such file or directory: '[...]STAR/cauliflower/genome/genome.ok'

I don't understand why snakemake would ignore the generating rule and just complain about a missing file instead, as it even takes the path from the very rule that should generate it...
rule STAR_genome:
    input: genome=lambda wildcards: config[wildcards.species]["genomefile"]
    output: ok=path.join(STAR_DIR, "{species}", "genome", "genome.ok")
    threads: 32
    envmodules:
        config["STAR"][0],
        config["STAR"][1]
    script:
        "scripts/Trinity_GG/STAR_genome.py"

############################################################################

rule STAR:
    input:
         genome=rules.STAR_genome.output.ok,
         r1=rules.trim_galore.output.r1,
         r2=rules.trim_galore.output.r2
    output:
        bam=path.join(STAR_DIR, "{species}_{rep}_Aligned.sortedByCoord.out.bam")
    threads: 32
    envmodules:
        config["STAR"][0],
        config["STAR"][1]
    script:
        "scripts/Trinity_GG/STAR.py"

And here is the full traceback, just in case it could help.
    Traceback (most recent call last):
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/__init__.py", line 751, in snakemake
    keepmetadata=keep_metadata,
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/workflow.py", line 1000, in execute
    success = scheduler.schedule()
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/scheduler.py", line 444, in schedule
    run = self.job_selector(needrun)
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/scheduler.py", line 731, in job_selector_greedy
    c = list(map(self.job_reward, jobs))  # job rewards
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/scheduler.py", line 814, in job_reward
    input_size = job.inputsize
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/jobs.py", line 378, in inputsize
    self._inputsize = sum(f.size for f in self.input)
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/jobs.py", line 378, in <genexpr>
    self._inputsize = sum(f.size for f in self.input)
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/io.py", line 239, in wrapper
    return func(self, *args, **kwargs)
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/io.py", line 254, in wrapper
    return func(self, *args, **kwargs)
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/io.py", line 553, in size
    return self.size_local
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/io.py", line 558, in size_local
    self.check_broken_symlink()
  File "/cluster/easybuild/broadwell/software/mflow/0.0-foss-2019b-Python-3.7.4/lib/python3.7/site-packages/snakemake-5.27.4-py3.7.egg/snakemake/io.py", line 563, in check_broken_symlink
    if not self.exists_local and os.lstat(self.file):
FileNotFoundError: [Errno 2] No such file or directory: '[...]/Cauliflower_Test/STAR/cauliflower/genome/genome.ok'

A: with the help of command snakemake --debug-dag I found that I had an error in the config call at
input: genome=lambda wildcards: config[wildcards.species]["genomefile"]

The right name was "genome_file" which was mentioned nowhere, but the debug-dag stated:
    candidate job STAR
    wildcards: species=cauliflower, rep=A
    file [...]/Cauliflower_Test/Alignmentscores/cauliflower_align_rate.txt:
    No producers found, but file is present on disk.
    Error:
      KeyError: 'genomefile'
    Wildcards:
      species=cauliflower
    Traceback:
      File "[...]/workflows/Trinity_GG.smk", line 9, in <lambda>

Hope this helps someone else, it costed me some hours and a lot of nerves...


text:
Q: Fixing bug in removing duplicates from sorted linked list I'm trying to remove duplicates from a sorted linked list. I have written the algorithm but still missing a core bug logic that I can't trace.
Consider the list
1->2->3->3->4->4->5
Output should be 1 - > 2 - > 5
The program works fine for a simple case, like 1>2>2>3, but for multiple duplicates like 1>2>2>3>3>5 it outputs 1>3>5
Here is a complete program:
struct Node
{
    Node* next;
    int val;
    Node()
    {

    }
};

int main()
{
    Node* n1 = new Node();
    n1->val = 1;
    Node* n2 = new Node();
    n2->val = 2;
    n1->next = n2;
    Node* n3 = new Node();
    n3->val = 3;
    n2->next = n3;
    Node* n4 = new Node();
    n4->val = 3;
    n3->next = n4;

    Node* n5 = new Node();
    n5->val = 4;
    n4->next = n5;

    Node* n6 = new Node();
    n6->val = 4;
    n5->next = n6;

    Node* n7 = new Node();
    n7->val = 5;
    n6->next = n7;
    n7->next = nullptr;

    Node* fast = n1->next;
    Node* slow = n1;
    Node* temp = n1;
    Node* prevSlow = nullptr;
    while (slow != nullptr && fast != nullptr)
    {

        if (fast->val == slow->val)
        {
            prevSlow->next = fast->next;
            fast = fast->next;
            slow->next = prevSlow->next;
        }
        else {
            prevSlow = slow;
            slow = slow->next;
            fast = fast->next;
        }
    }

}

A: For starters this constructor
Node()
{

}

does not make a sense. Remove it.
The statement
prevSlow->next = fast->next;

in this if statement
if (fast->val == slow->val)
{
    prevSlow->next = fast->next;
    fast = fast->next;
    slow->next = prevSlow->next;
}

in general can invoke undefined behavior because initially the pointer prevSlow is set to nullptr
Node* prevSlow = nullptr;

Pay attention to that the node n1 is the head node of the list. It can be changed in the process of removing duplicates. Also you need to free memory of removed nodes.
The algorithm can be implemented the following way
auto is_duplicate = [] ( const Node *node )
{
    return node->next != nullptr && node->val == node->next->val;
};

for ( Node **current = &n1; *current != nullptr; )
{
    if ( is_duplicate( *current ) )
    {
        do
        {
            Node *tmp = *current;
            *current = ( *current )->next;
            delete tmp;
        } while ( is_duplicate( *current ) );

        Node *tmp = *current;
        *current = ( *current )->next;
        delete tmp;
    }
    else
    {
        current = &( *current )->next;
    }
}


text:
Q: Free vector space characterization of tensor products Problem 3 pg. 12 from Greub's Multilinear Algebra.
Show that $C(S) \otimes C(T)$ is isomorphic to $C(S \times T)$ where S,T are sets, and C(T) is the free vector space on T.
My first instinct is to show that $C(S \times T)$ satisfies the universal property of the tensor product on $C(S) \times C(T)$ but I'm not sure where to begin.

A: The universal property of the tensor product says that the tensor product $C(S) \otimes C(T)$ along with the bilinear map $\phi: C(S)\times C(T) \rightarrow C(S)\otimes C(T)$ (given by $(v,w) \rightarrow v\otimes w$) satisfies the property that given any vector space $V$ and a bilinear map $F$ from $C(S) \times C(T)$ to $V$, there exists a unique linear map $f: C(S) \otimes C(T)\rightarrow V$, such that $F = f \circ \phi$.
Now consider the vector space $C(S\times T)$ along with the bilinear map $\psi:C(S)\times C(T)\rightarrow C(S\times T)$, given by $(e_s,e_t)\rightarrow e_{(s,t)}$, where $s\in S, t\in T$ and $e_x$ is the basis element corresponding the the element $x$ in the respective free vector spaces. Observe that since we want $\psi$ to be bilinear, for arbitrary vectors $v = \sum_{s\in S}a_se_s \in C(S)$ and $w = \sum_{t\in T}b_te_t \in C(T)$, $\psi(v,w)$ must be given by
\begin{align}
\psi(v,w) &= \psi\left(\sum_{s\in S}a_se_s,\sum_{t\in T}b_te_t\right) \\
&= \sum_{s\in S}a_s \psi\left(e_s,\sum_{t\in T}b_te_t\right) \\
&= \sum_{s\in S,t\in T}a_sb_s \psi\left(e_s,e_t\right) \\
&= \sum_{s\in S,t\in T}a_sb_s e_{(s,t)}
\end{align}
Here $a_s$ and $b_t$ are elements in your base field, being zero for all but finitely many $s\in S$ and $t\in T$. This makes sure that the sum at the end is also finite and hence is an element of $C(S\times T)$. Now this is well defined, since basis representations for $v$ and $w$ are unique, and can be checked to be bilinear.
Now to check for the universal property, consider a bilinear map $G: C(S)\times C(T) \rightarrow V$. We wish to show that there exists a unique linear map $g:C(S\times T)\rightarrow V$ such that $G = g\circ \psi$. Observe that the equality $G = g\circ\psi$ forces that $g(e_{(s,t)})=g(\psi(e_s,e_t))=G(e_s,e_t)$ for $s\in S$ and $t\in T$. Since elements of the form $e_{(s,t)}$ form a basis for $C(S\times T)$, this uniquely determines the linear map $g$. Now one must check that the linear map $g$ given by $g(e_{(s,t))} = G(e_s,e_t)$ satisfies $G = g\circ\psi$, which I leave to you as an exercise.


text:
Q: GWT Request builder, send data from one port to another port I hava a GWT project running on port 3000, and i have a Java project running on port8080. Now i just want to send a string from port 3000 to 8080. Would it be possible by using GWT request builder? or how to make this process happen by using other technology?
I also need data to be sent from port 8080 to port 3000....

A: Yes it is possible.
I'm assuming your java project should be a service/webapp, since you have mentioned the port in which your java project is running is 8080(default tomcat port).
Your access from GWT project running on port 3000 to java project running on port 8080 is a Cross Site Request.
References on Cross site request:

*

*http://www.gwtproject.org/doc/latest/tutorial/Xsite.html
(Please read section : Access Restrictions: Same Origin Policy)

*GWT RequestBuilder - Cross Site Requests


text:
Q: In a hash table, are keys stored with their corresponding values? As an example, I'm writing a hash table that has names as keys and telephone numbers as data. Should it be a table of names combined with numbers (i.e. a table of structs) or just a table of just the numbers? Because if you're looking up someone's telephone number, you already know their name, so I don't see the point of storing the name with the number.

A: There are some general suggestions for some problems you are facing on:

*

*If you want to quickly look up data based on some key, like in a dictionary or a
phone-book, use a map.

*If the values are unique, have operator < defined, and you want quick look-ups, use
a set.

*If you repeatedly want the largest value, use a priority_queue.

*If you want to quickly add values but you don't need to access them often, use a list.

*If you want to quickly access values at a specific position, use a vector.

Back to your question a HashTable is a table implementation with constant time access. Like a map, you can store key-value pair associations in the hash table. However, hash tables don't store the data in sorted order. A hash table is implemented with a array at the top level. Each key is mapped to a slot in the array by a hash function. But Sometimes it useful to combine containers to get the best advantages of each container. Like your phone-book.
For instance, suppose we want to look up records based on more than one key type.
John-Romero
5673-67854

Alice-Nice
3452-878

We want to be able to look up the records by entering their name or phonenumber.  So we want 2 search keys for each record. (We assume all keys are unique.)  But a map only lets us have only one key per record, One solution is to create a master list of the records.  For each key type, create a map that contains iterators pointing to the record in the phone-book.
To make record insertion O(1), a list would be good for the phone-book.

Imagine a phonebook with 50,000 name/number pairings. Each number is a
  10 digit number. We need to create a data structure to lookup the name
  matching a particular phone number. Ideally, name lookup should be
  O(1) time expected, and the caller ID system should use O(n) memory (n
  = 50,000).

list<Record> phone_book;

To make look-ups O(1), a map would be best for the keys.
map<string, list<Record>::iterator> names;
map<int, list<Record>::iterator> phones;

We can print a record by dereferencing the iterator:
cout << *names["John-Romero"];

here is a sample program in Java with a single key
import java.util.*;
public class PhoneBook {

    /**
     * @param args the command line arguments.
     */
    public static void main(String[] args) {
        /* instantiate a Hashtable Object*/
        Hashtable dict = new Hashtable();
        /* it is just an iterator */
        Enumeration iterator;
        /* the temporary key value*/
        String tempKey;
        /* here we put some key and value */
        dict.put("Zahurul Islam",new Long(898989));
        dict.put("Naushad Uzzaman", new Long(676767));
        dict.put("Asif Iqbal", new Long(565656));
        dict.put("Mr.Pavel", new Long(232323));
        dict.put("Marzy Rahman",new Long(343434));
        dict.put("Mehedi Al mamun",new Long(234324));

        /* here we traverse the dict */
        iterator = dict.keys();
        while (iterator.hasMoreElements()) {
            Object key = iterator.nextElement();
            System.out.println("Name: "+ key +" Phone Number: "+ dict.get(key));
        }

        /* this is temporay key, if this is exist we just change the value
         * other wise we put the pair(key,value)  */
        tempKey = "Zahurul Islam";
        if(!dict.containsKey(tempKey)) {
            System.out.println("No such Name in this phone Book");
        } else {
            Long phoneNumber = (Long) dict.get(tempKey);
            long phNum = phoneNumber.longValue();
            System.out.println(phNum+ " This Phone Number of "+ tempKey + " is changed ");
            dict.put(tempKey, new Long(121212));
        }

        System.out.println("\nUpdated Phone book\n");
        iterator = dict.keys();
        while (iterator.hasMoreElements()) {
            Object key = iterator.nextElement();
            System.out.println("Name: "+ key +" Phone Number: "+ dict.get(key));
        }

    }

}

And here is other with 2-keys
import java.io.*;
import java.lang.reflect.Array;
import static java.lang.System.out;
import java.util.*;

/************************************************************************************
 * This class provides hash maps that use the hashing with separate chaining algorithm.
 * A hash table is created that is an array of buckets.  It restricts the number of
 * slots per bucket to one (just one key-value pair), but could easily be extended
 * to support multiple key-value pairs per bucket.
 */
public class HashSC <K, V>
       extends AbstractMap <K, V>
       implements Serializable, Cloneable, Map <K, V>
{
    /********************************************************************************
     * This inner class defines buckets that are stored in the hash table.
     */
    private class Bucket
    {
        K      key;       // alt. use K [] instead of K
        V      value;     // alt. use V [] instead of V
        Bucket next;
        Bucket (K k, V v, Bucket n) { key = k; value = v; next = n; }
    } // Bucket inner class

    /** The array of buckets making up the hash table.
     */
    private final Bucket [] hTable;

    /** The size of the hash table (number of home buckets)
     */
    private final int size;

    /** Counter for the number buckets accessed (for performance testing)
     */
    private int count = 0;

    /********************************************************************************
     * Construct a hash table that uses separate chaining.
     * @param cap  the capacity of the hash table
     */
    @SuppressWarnings("unchecked")
    public HashSC (int cap)
    {
        hTable = (Bucket []) Array.newInstance (Bucket.class, size = cap);
    } // HashSC

    /********************************************************************************
     * Return a set view of map containing all the entries as pairs of keys and values.
     * @return  the set view of the map
     */
    public Set <Map.Entry <K, V>> entrySet ()
    {
        Set <Map.Entry <K, V>> enSet = new HashSet <> ();
        for (int i = 0; i < size; i++) {
            for (Bucket b = hTable [i]; b != null; b = b.next) {
                enSet.add (new AbstractMap.SimpleEntry <K, V> (b.key, b.value));
            } // for
        } // for

        return enSet;
    } // entrySet

    /********************************************************************************
     * Given the key, look up the value in the hash table.
     * @param key  the key used for look up
     * @return  the value associated with the key
     */
    public V get (Object key)
    {
        int i = h (key);
        for (Bucket b = hTable [i]; b != null; b = b.next) {
            count++;
            if (b.key.equals (key)) return b.value;
        } // for
        return null;
    } // get

    /********************************************************************************
     * Put the key-value pair in the hash table.
     * @param key    the key to insert
     * @param value  the value to insert
     * @return  null (not the previous value)
     */
    public V put (K key, V value)
    {
        int i = h (key);
        hTable [i] = new Bucket (key, value, hTable [i]);
        return null;
    } // put

    /********************************************************************************
     * Return the size (number of home buckets) in the hash table.
     * @return  the size of the hash table
     */
    public int size ()
    {
        return size;
    } // size

    /********************************************************************************
     * Print the hash table.
     */
    private void print ()
    {
        out.println ("Hash Table (hashing with separate chaining)");
        out.println ("-------------------------------------------");
        for (int i = 0; i < size; i++) {
            out.print (i + ":\t");
            boolean notFirst = false;
            for (Bucket b = hTable [i]; b != null; b = b.next) {
                if (notFirst) out.print ("--> ");
                out.print ("[ " + b.key + " ]\t");
                notFirst = true;
            } // for
            out.println ();
        } // for
        out.println ("-------------------------------------------");
    } // print

    /********************************************************************************
     * Hash the key using the hash function.
     * @param key  the key to hash
     * @return  the location of the bucket chain containing the key-value pair
     */
    private int h (Object key)
    {
        return key.hashCode () % size;
    } // h

    /********************************************************************************
     * The main method used for testing.
     * @param  the command-line arguments (args [0] gives number of keys to insert)
     */
    public static void main (String [] args)
    {
        HashSC <Integer, Integer> ht_i = new HashSC <> (11);
        HashSC <String, Integer>  ht_s = new HashSC <> (11);
        int nKeys = 30;
        if (args.length == 1) nKeys = Integer.valueOf (args [0]);
        for (int i = 1; i < nKeys; i += 2) {
            ht_i.put (i, i * i);
            ht_s.put ("s" + i, i * i);
        } // for
        ht_i.print ();
        ht_s.print ();
        for (int i = 0; i < nKeys; i++) {
            out.println ("key = " + i + "  value = " + ht_i.get (i));
            out.println ("key = s" + i + " value = " + ht_s.get ("s" + i));
        } // for
        out.println ("-------------------------------------------");
        out.println ("Average number of buckets accessed = " + ht_i.count / (double) nKeys);
        out.println ("Average number of buckets accessed = " + ht_s.count / (double) nKeys);
    } // main

} // HashSC class

I think you can compare the efficiency of both solutions (the last code needs to be modified to be a phone-book) so you can decide which better suits your needs.


text:
Q: Error Laravel 5.6, Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException" I have adjust controller name with route and send form that post method but it didnt work, i send it from modal
I have add {{ method_field('patch') }} but it still didnt work
This is from view :
<form action="{{route('edit kode', 'test')}}" method="post">
                {{ method_field('patch') }}
                {{ csrf_field() }}

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        clear
                    </button>

Edit Data

                                Kode
                                <input type="hidden" class="form-control" id="modalidkode">
                                <input type="text" class="form-control" id="modalkode" readonly>

                                Nama Kode
                                <input type="text" class="form-control" id="modalnamakode" required>

                    <button type="button" class="btn btn-danger" data-dismiss="modal"
                            style="margin-right: 10px">Batal
                    </button>
                    <button type="submit" class="btn btn-info">Simpan Perubahan</button>

Controller
public function editCode(Request $request){
    dd($request->all());
    $edCode="05.01";
    return redirect()->back()->withSuccess($edCode. " changed");
}

Route
Route::post('/pengaturan/edit', 'AllCodeController@editCode')->name('edit kode');

A: You're expecting the request to be a POST request in your routes, but your form is submitting a PATCH request (because of the method_field('patch') at the top of your form). Either remove the method_field() call, or change Route::post(...) to Route::patch(...).
You can read more about form method spoofing in the Laravel documentation:

HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method:

<form action="/foo/bar" method="POST">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>


text:
Q: How to find this integral? Any way to solve it quickly? Evaluate the following integral:
$$\int\frac{x^5}{(x-1)^2(x^2+1)}dx $$
Was trying to solve it with long division etc for an hour but didn't get to a solution. What is a simple way to solve this?

A: Use partial fraction decomposition:
$$
\int\frac{x^{5}}{\left(x-1\right)^{2}\left(x^{2}+1\right)}dx=\int\left(-\frac{1}{2\left(x^{2}+1\right)}+x+\frac{2}{x-1}+\frac{1}{2\left(x-1\right)^{2}}+2\right)dx
$$
See also Wolfram.


text:
Q: Upgrade SQL Server 2014 Failover Cluster to SQL Server 2016 Availability Group on Windows Server 2016 In our current set up we have 2 node SQL failover cluster in data center DC1 with mirroring enabled. And similarly in DC 2 a 2 node SQL failover cluster. DC1 acts as primary via DB mirroring in one point of time and DC2 mirror.
 Above runs on Windows server 2012R2
How can I convert the above setup from sql cluster to get cluster so that can leverage always on. I know this is sort of s big question but needed to know how can this be achieved with some overview and I can do some poc on that. We are thinking to upgrade to sql 2016 on Windows 2016 if possible.
Please guide for any real time experiences or blogs I can go through to do such migration.
Edit-- Per Answer below which needs the DR server at different DC to be out for route seems to be last option but i will still test to figure out the timings.
Also, is it possible to have setup like configure LS on current prod server with 4 node new built multi site cluster for alwayson AG? And during cutover we can simply stop the LS job on prod and convert the LS secondary on 4 node cluster to alwayson AG configuration

A: To migrate from two Failover Clustered Instances (FCI) to an Availability Group (AG) that spans four Availability Replicas is fairly straight forward but somewhat of a lengthy process. Also, some downtime is required to point your application to the Availability Group Lister and manually fail over to one of the Secondary Replicas.
This is a high level overview of the process so use the links provided to plan:

*

*Disable Database Mirroring

*Completely uninstall the FCI and destroy Windows Cluster at DC2

*

*Uninstalling a SQL Server Clustered Instance

*Install Standalone SQL Instances on the two nodes at DC2

*Join the two new stand-alone servers at DC2 to Cluster at DC1 and configure the AG

*

*Combine a failover cluster instance and Availability Groups

*Configure Availability Group on a multisubnet cluster

*Take down time to fail over to to a Secondary Replica in DC2 and update Application to point to Listener

*Remove FCI from AG

*

*Remove a secondary replica from an Always On Availability Group

*Completely uninstall the FCI at DC1

*Repeat Step 3 at DC1

*Add new stand-alone instances to AG

*

*Add a secondary replica to an Always On Availability Group
All of this can be done on SQL Server 2014. There are some benefits to upgrading to 2016 but I would recommend you read this to help plan as there are a lot of similar steps to upgrade.


text: Q: Cursor/Touchpad lag while using Battery Power in Ubuntu 22.04.1 LTS Long time reader, first time caller. I'm experiencing a cursor lag in Ubuntu 22.04 but only when plugged into battery power. Once unplugged, the cursor moves at the expected rate. Also of note is that once I unplug from battery power, it takes up to a minute before the computer registers the disconnect (makes the disconnect noise and removes the charging icon in the top corner). I'm using an Asus Zenbook 14 and would appreciate any advice. Thanks!


text:
Q: Giving a users without access to a document library access to a Docset I want to give a couple of users who don't have access to a document library, access to the whole of a document set in that library including its welcome page. Doesn't seem an easy task as the welcome page lives in the hidden forms subfolder of the document library. I would have to give these users read access to the whole library which I don't want?

A: I don't see any other solution other than giving read permission to the root of the Library and then uniquely securing items in the Library so those users will only see Document Set.
Below is another Solution you can try out - I hope it should work.
Document Set is a kind of Folder. So idea is - Using SharePoint Designer open out-of-the box Welcome Page, Copy its content and create a new Page in Pages Library (Assuming the users has permission to this library).
Now using PowerShell - Get Folder (Document Set) and Set WelcomePage to the new Page that you created above.