text:
Q: Can Dolphin file-manager administer the desktop outside Plasma/KDE? I am trying to set Dolphin to manage the desktop in LXQt installed on top of Kubuntu 18, instead of PCManFM-Qt, but this answer says that Dolphin cannot do that, (also this answer) not  even on Plasma KDE, but that Kwin does it.
I don't understand exactly if that's correct and what could that mean. As LXQt desktop is installed in Kubuntu, Kwin is installed on my system - and I have set it also the default window manager in the LXQt desktop environment.
What I expect is a folder clicked on the desktop to be opened in Dolphin, and the right-click context menu of a selected file/folder to be the one set for Dolphin - instead of PCManFM-Qt.
I am posting this in order to get a more clear answer.


text:
Q: Wrapping C++ class in Objective-C I have a C++ library that doesn't use namespaces. I want to port it to Objective-C. The problem is the name collisions between the two. I want it to have the same name in Objective-C that is the name of the C++ object. But, I just can't figure out the best way to do this without it just becoming a mess. I am hoping for a solution to this.

A: Prefix all your Objective-C classes in the same way as you would writing a framework on the Mac and Apple does with its frameworks.

A: You can use #define and #undef to temporarily rename the classes/functions etc in your code - just make sure they are undef'ed when calling the C++ code.
e.g. in the header(s) for your wrapper have #define Bar_Function Foo_Function, then surround the bits of code that call the library's Bar_Function with #undef Bar_Function and #define Bar_Function Foo_Function
Now the only problem comes when you need to export your own Bar_Function...
Don't do this though - its silly, just work around it. :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: instance for RegexMaker Regex CompOption ExecOption Text missing when using (=~) I try to find a way to use regex to search in text and not adding a dependency for template haskell.
My simplistic example is
import Text.Regex.TDFA

d = t1 =~ pat4 :: Text
pat4 = "([12][0,6-9][0-9][0-9])" :: Text
t1 = "foodiebar 1933 some more 19456 text " :: Text

The code works for Text.Regex.PCRE for String but when I change to Text and import Text.Regex.TDFA the compiler produces:
RegexMaker Regex CompOption ExecOption Text

what is additionally required?

A: Missing is an import of the instances in Text.Regex.TDFA.Text (only the instances). Thus:
import Text.Regex.TDFA
import Text.Regex.TDFA.Text ()

It is unfortunate that there is so little up-to-date documentation and two many different implementations of regex for haskell. I took hours to identify which packages work together.
I found the blog useful.


text:
Q: How to get SOCKS5 capable application proxied through OpenVPN without running everything through VPN on Gnome 3 How can I selectively tunnel by application in Gnome using a remote OpenVPN server or use the arbitrary application's built-in SOCKS5 proxy support to connect to a local "translation" server that forwards SOCKS packets as OpenVPN packets.
Blacklisted Applications -> remote OpenVPN server -> internet

and
Whitelisted Applications -> internet

OR
Application -> local SOCKS5 server -> remote OpenVPN server -> internet

or maybe I'm over thinking it. All I know is I can't tunnel everything through the VPN, but I also cannot let certain applications through without pushing through the OpenVPN server.


text:
Q: Second level cache parent entity after native delete child with on delete set null I'm using the following code to evict cached entities deleted by a native query:
 entityManager.getEntityManagerFactory().getCache().evict( ChildEntity.class );

If this entity type is referenced from other entity ParentEntity, what's the behaviour when accesing a ChildEntity referenced from a previously cached ParentEntity?
ParentEntity is the foreign key owner with on delete set null, so the child id will be null in database after delete.
I think that the cached ParentEntity already knows the old child id, so will it try to get the child entity by id from database and fail? If so, should I also evict all entities that link to ChildEntity?

A: After testing with Hibernate 5.4.15 it seems that when loading the Parent entity from second level cache it will try to load the obsolete child and throw an EntityNotFoundException that will cascade and ultimately return a null (missing) Parent entity, but the Parent entity still exists in database.
Opened hibernate bug HHH-14058 that contains the sample test repository.


text:
Q: git tracked a directory and ignored the subdirectories The contents of my folder are:
.cpanel/
.git/
.trash/
.vim/
bin/
etc/
laravel/
logs/
mail/
perl5/
php/
public_html/
repo.git/
ssl/

Here is my .gitignore file
.*
~/.gitignore
*.git/
access-logs/
etc/
logs/
mail/
php/
ssl/
tmp/
trash/
vendor/
error_log
\.bak\.

When I clone from my git repository, the laravel folder in my local machine shows as:
The contents of ls -la laravel from local machine
total 8
drwxrwxr-x 2 mfissehaye mfissehaye 4096 ኦክተ 22 05:34 .
drwxrwxr-x 5 mfissehaye mfissehaye 4096 ኦክተ 22 05:34 ..

The contents of ls -la laravel from server
total 124
drwxr-xr-x  5 malameng malameng  4096 2015-10-22 02:52 .
drwxr-xr-x 18 malameng nobody    4096 2015-10-22 03:04 ..
drwxr-xr-x 13 malameng malameng  4096 2015-03-20 05:54 app
-rw-r--r--  1 malameng malameng  2452 2015-03-17 09:44 artisan
drwxr-xr-x  2 malameng malameng  4096 2015-03-20 05:55 bootstrap
-rw-r--r--  1 malameng malameng   798 2015-03-17 09:44 composer.json
-rw-r--r--  1 malameng malameng 68065 2015-03-17 09:44 composer.lock
-rw-r--r--  1 malameng malameng   146 2015-03-17 09:44 CONTRIBUTING.md
-rw-r--r--  1 malameng malameng   606 2015-10-21 09:25 error_log
-rw-r--r--  1 malameng malameng    12 2015-03-17 09:44 .gitattributes
-rw-r--r--  1 malameng malameng   100 2015-03-17 09:44 .gitignore
-rw-r--r--  1 malameng malameng   567 2015-03-17 09:44 phpunit.xml
-rw-r--r--  1 malameng malameng  2051 2015-03-17 09:44 readme.md
-rw-r--r--  1 malameng malameng   519 2015-03-17 09:44 server.php
drwxr-xr-x 24 malameng malameng  4096 2015-03-20 05:54 vendor

Something I did before pushing my changes to the repo
The laravel folder had its own .git folder. I removed that. I didn't wanna deal with submodule and stuff.


text:
Q: Missing vertices in sphere model I'm learning OpenGL and I'm working on creating my own sphere model. I was able to draw a complete sphere, although with some puzzling results. I'm wondering if someone can explain (and possibly correct) my code.
The rationale: build triangles using carthesian coordinates calculated from polar coordinates. The number of subdivisions tells me the steps in phi or theta radians to generate the sphere point. From a particular point P(phi, theta), I build the other edges of the sector for [phi, delta_phi], [theta, delta_tetha], with phi varying from [0, pi] (180 degrees) and tetha from [0, 2*pi] (360 degrees).
This is the code I came up with (I'm using QT objects, but it should be pretty straitghforward):
QVector3D polarToCarthesian(float rho, float phi, float theta)
{
    float r = qSin(phi) * rho;
    float y = qCos(phi) * rho;

    float x = r * qSin(theta);
    float z = r * qCos(theta);

    return QVector3D{x, y, z};
}

void make_sector(QVector<QVector3D>& mesh, float phi, float theta, float rho, float deltaPhi, float deltaTheta)
{
    QVector3D p1 = polarToCarthesian(rho, phi, theta);
    QVector3D p2 = polarToCarthesian(rho, phi, theta + deltaTheta);
    QVector3D p3 = polarToCarthesian(rho, phi + deltaPhi, theta);
    QVector3D p4 = polarToCarthesian(rho, phi + deltaPhi, theta + deltaTheta);

    // First Triangle
    mesh.push_back(p1);
    mesh.push_back(p1); // Normal
    mesh.push_back(p3);
    mesh.push_back(p3); // Normal
    mesh.push_back(p2);
    mesh.push_back(p2); // Normal

    // Second Triangle
    mesh.push_back(p2);
    mesh.push_back(p2); // Normal
    mesh.push_back(p3);
    mesh.push_back(p3); // Normal
    mesh.push_back(p4);
    mesh.push_back(p4); // Normal
}

void build_sphere(QVector<QVector3D>& mesh, int ndiv)
{
    const float PHI_MAX = static_cast<float>(M_PI);
    const float THETA_MAX = static_cast<float>(M_PI) * 2;

    const float delta_phi = PHI_MAX / ndiv;
    const float delta_theta = THETA_MAX / ndiv;

    for (int i = 0; i < ndiv; ++i) {
        float phi = i * delta_phi;
        for (int j = 0; j < ndiv; ++j) {
            float theta = j * delta_theta;
            make_sector(mesh, phi, theta, 1.0f, delta_phi, delta_theta);
        }
    }
}

// Then I can generate the sphere with
build_sphere(sphere_mesh, 10);

However, I cannot get a complete sphere unless I change the iteration for phi from ndiv iterations to 3 * ndiv iterations. I don't understand why! Phi should vary from 0 to PI to cover the whole Y axis while Theta from 0 to 2 * pi should cover the XZ plane.
Can somebody explain what's happening and why 3 * ndiv works?

A: phi should go from -π/2 to +π/2, not from 0 to π:
float phi = i * delta_phi - (M_PI / 2);

Also, you appear to have your r and y calculations the wrong way around.  You want r to be maximum at the equator (when phi == 0).
I think your code may have worked (albeit producing twice as many polygons as it should have) if you had stuck at 2 * ndiv.  As it is, going from 0 to π only puts polygons in the northern hemisphere, so you have to keep going beyond that to have any polygons in the southern hemisphere.
p.s. there's no 'h' in cartesian ;)


text:
Q: Reopen Dexie Database with Tampermonkey As per my previous post, I was referred to create a new post.
As seen in the comments, there is a trail of progression for the issue, I'll rephrase here in this post:
I'm using a TamperMonkey script in FireFox.
I'm trying to persist a Dexie object/database into TamperMonkey's local storage with GM.setValue('unique-dexie-db-name', dexieDBvariable);
However when I go to retrieve this value (ex. I store this on google.com, and retrieve this on yahoo.com) with var dexieDB = GM.getValue('unique-dexie-db-name'); My returned object value is not a Dexie database object, but rather something else I can't use as a database.
My question: I'm unsure, but I think when storing this Dexie Database into TamperMonkey, it gets stored as a string, and, I should try to somehow JSON.stringify() the object fully in order to be able to reproduce and re-create it when I need it in the GM.getValue() call. How do I store this Javascript object as a string in order to be able to retrieve the value again as a whole later?
This is my working example code;
https://gist.github.com/n-bell/b375c80b638d3a59a250e903afb4a36b.js
https://gist.github.com/n-bell/b375c80b638d3a59a250e903afb4a36b
(second link looks better formatted in browser)
And, as stated before, I've tried playing around with JSON.parse() / JSON.stringify() but I'm not sure this is the path to go down.


text:
Q: How to create a new index level with columns name in Pandas? I would like to add a new level to the index of a dataframe, based on columns name. How can i do that ?
df
    home        city
A   -0.166809   0.213299
B   -0.040300   0.034583
C   -0.002245   0.001058

Desired result
A   home  -0.166809
    city   0.213299
B   home  -0.040300
    city   0.034583
C   home  -0.002245
    city   0.001058

I can build the multiindex with this but how can i create a new dataframe and map the data  ?
idx = pd.MultiIndex.from_product ([df.index, df.columns])
pd.DataFrame(df.values, ix)

ValueError: Shape of passed values is (3, 2), indices imply (6, 2)

A: You can use df.stack()
print(df.stack())

A  home   -0.166809
   city    0.213299
B  home   -0.040300
   city    0.034583
C  home   -0.002245
   city    0.001058
dtype: float64

Back to your code, you can try numpy.ravel to flatten the df.values to match the idx shape (idx has 6 items, df.values only return rows which are 3)
idx = pd.MultiIndex.from_product([df.index, df.columns])
df = pd.DataFrame(df.values.ravel(), idx)

print(df)

               0
A home -0.166809
  city  0.213299
B home -0.040300
  city  0.034583
C home -0.002245
  city  0.001058


text:
Q: How to concatenate two collections by index in LINQ What could be a LINQ equivalent to the following code?
string[] values = { "1", "hello", "true" };
Type[] types = { typeof(int), typeof(string), typeof(bool) };

object[] objects = new object[values.Length];

for (int i = 0; i < values.Length; i++)
{
    objects[i] = Convert.ChangeType(values[i], types[i]);
}

A: Assuming both arrays have the same size:
string[] values = { "1", "hello", "true" };
Type[] types = { typeof(int), typeof(string), typeof(bool) };

object[] objects = values
    .Select((value, index) => Convert.ChangeType(value, types[index]))
    .ToArray();

A: object[] objects = values.Select((s,i) => Convert.ChangeType(s, types[i]))
                         .ToArray();

A: .NET 4 has a Zip operator that lets you join two collections together.
var values = { "1", "hello", "true" };
var types = { typeof(int), typeof(string), typeof(bool) };
var objects = values.Zip(types, (val, type) => Convert.ChangeType(val, type));

The .Zip method is superior to .Select((s, i) => ...) because .Select will throw an exception when your collections don't have the same number of elements, whereas .Zip will simply zip together as many elements as it can.
If you're on .NET 3.5, then you'll have to settle for .Select, or write your own .Zip method.
Now, all that said, I've never used Convert.ChangeType. I'm assuming it works for your scenario, so I'll leave that be.


text:
Q: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'find') my screen
import axios from 'axios';
import { CART_ADD_ITEM } from '../constants/cartConstants'

export const addToCart = (id,qty) => async(dispatch,getState) => {
    const {data} = await axios.get(`http://127.0.0.1:8000/api/products/${id}`)

    dispatch({
        type:CART_ADD_ITEM,
        payload: {
            product:data._id,
            name:data.name,
            image:data.image,
            price:data.price,
            countInStock: data.countinStock,
            qty
        }
    })
    localStorage.setItem('cartItems',JSON.stringify(getState().cart.cartItems))
}

my reducer
import { startTransition } from 'react'
import { CART_ADD_ITEM } from '../constants/cartConstants'

export const cartReducer = (state = {cartItems:[]},action)=> {
    switch (action.type) {
        case CART_ADD_ITEM:
            const item = action.payload
            const existItem = state.cartItems.find(x => x.product === item.product)
            if(existItem){
                return{...state,
                cartItems: state.cartItems.map(x =>
                    x.product === existItem.product ? item: x)}
            }else{
                return{
                    ...state,
                    cartItems:[...state.cartItems,item]
                }
            }
        default:
            return state
    }
}

Action
import axios from 'axios';
import { CART_ADD_ITEM } from '../constants/cartConstants'

export const addToCart = (id,qty) => async(dispatch,getState) => {
    const {data} = await axios.get(`http://127.0.0.1:8000/api/products/${id}`)

    dispatch({
        type:CART_ADD_ITEM,
        payload: {
            product:data._id,
            name:data.name,
            image:data.image,
            price:data.price,
            countInStock: data.countinStock,
            qty
        }
    })
    localStorage.setItem('cartItems',JSON.stringify(getState().cart.cartItems))
}

Error when i'm trying to put something in a cart
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'find')
at cartReducer (cartReducers.js:8:1)
Probably it is because of null product, but how it becames null i don't know


text:
Q: Database updates not readable while PHPunit WebTestCase (Symfony 5.1) I have a problem asserting updates made by a form are really written in the database.
I explain, I first do a create test (testCreateLactationForm), very similar to the edit test. In that firs test y check the record is finally inserted and all works fine:
        $finalRecords = $qb->where($qb->expr()->like('p.comments', ':comments'))
            ->setParameter('comments', '%'.$payload["form[comments]"].'%')
            ->getQuery()
            ->getResult();

        $this->assertTrue(count($finalRecords) == (count($initialRecords) + 1));

After that, I made a dependant test where I locate las record, navigate to edit form, and update the modality and comments fields. In last line, when asserting Modality is equal to ONE_HOUR_REDUCTION, entity modality field remains with original creation value, so it fails, while in database the value was succesfully updated.
class HhrrProceduresControllerTest extends WebTestCase
{
    /** @var \Doctrine\ORM\EntityManager */
    private $entityManager;
    private $client;

    public function setUp()
    {
        parent::setUp();

        $this->client = self::createClient();
        $kernel = self::bootKernel();
        $this->entityManager = $kernel
            ->getContainer()
            ->get('doctrine')
            ->getManager();

        $this->hrmLogger = $kernel
            ->getContainer()
            ->get('monolog.logger.hrm');

    }

    [...]

    /**
     * @depends testCreateLactationForm
     */
    public function testEditLactationProcedure()
    {
        $payload = [
            "hhrr_procedure_lactation[modality]" => HhrrProcedureLactationModality::ONE_HOUR_REDUCTION,
            "hhrr_procedure_lactation[iniDate]" => "07/02/2022",
            "hhrr_procedure_lactation[endDate]" => "13/02/2022",
            "hhrr_procedure_lactation[hhrrProcedure][comments]" => "XXX--TEST--XXX | UPDATED",
        ];

        $qb = $this->entityManager->getRepository(HhrrProcedure::class)->createQueryBuilder('p');
        $initialRecord = $qb->orderBy('p.id', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getResult();

        $this->client->followRedirects(true);
        $this->client->request('GET', '/rrhh/tramites/'.$initialRecord[0]->getId().'/editar-tramite/', [], [], ['HTTP_X-AUTH-USERNAME' => $this->logged_in_user]);
        $crawler = $this->client->submitForm('Siguiente', $payload);

        $this->writeOutput(__FUNCTION__, $this->client->getResponse()->getContent());

        // verificar retorno correcto de la página
        $this->assertSame(200, $this->client->getResponse()->getStatusCode());

        /** @var HhrrProcedure $updatedRecord */
        $updatedRecord = $this->entityManager->getRepository(HhrrProcedure::class)->find($initialRecord[0]->getId());
        /** FAILS --> **/ $this->assertEquals($updatedRecord->getHhrrProcedureLactation()->getModality(),HhrrProcedureLactationModality::ONE_HOUR_REDUCTION);
    }

In addition to that, if I try to write aditional dependant test, assertion is ok...
    /**
     * @depends testEditLactationProcedure
     */
    public function testEditLactationProcedureAssertion()
    {
        $qb = $this->entityManager->getRepository(HhrrProcedure::class)->createQueryBuilder('p');
        $initialRecord = $qb->orderBy('p.id', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getResult();
        $this->assertEquals($initialRecord[0]->getHhrrProcedureLactation()->getModality(),HhrrProcedureLactationModality::ONE_HOUR_REDUCTION);

    }

Some help? Thanks!!

A: Doctrine entities are persisted in an internal cache (which is not the case when you use findBy methods, that load a new documents). You need to use
EntityManagerInterface's refresh($entityObject) or clear() in order to get fresh data from the database.


text:
Q: NetBeans+Android: after update i have error: build.xml:77: Android Target is not set Today Netbeans found new update of android plugin. and i installed it. After that, all my project had "broken platform" instead of Android.2.3. I after i choose  platform again ,in project properties, it looks OK. But i can't build project - i get error
build.xml:77: Android Target is not set.
I did not change anything in my projects, now they just don't build..
any ideas?

A: Adding "project.properties" brings up a new error:
Target "debug" does not exist in the project
Edit: I feel stupid now! :-)
Of course you have to update the android-sdk to revision 15 first.
http://www.nbandroid.org/ explains why.

A: I think this is bug of plugin, in build.xml.
Add to build.xml:

<property file="project.properties" />

A: Update your Android SDK to recent version of Tools (revision 15 I think). Then update your project(s) as described in http://developer.android.com/sdk/tools-notes.html in a section related to tools revision 14.
There are few more comments on that at http://www.nbandroid.org/2011/10/synch-with-latest-android-sdk.html
-Radim

A: Try this:
Open project.properties file
and check if it contains
target=android-19
if not manually type this.


text:
Q: run kafka producer from my local gives me Exception in thread "main" kafka.common.FailedToSendMessageException: Failed to send messages after 3 I am trying to stream data from Twitter and store in a topic. I am using single broker everything is set up on one server. I am using ec2 instance and configured listeners = PLAINTEXT://aws_private_ip:9092 and advertised.listeners=PLAINTEXT://aws_private_ip:9092, everything is working fine when trying to send and receive messages from the ec2 instance.
But when I try to run producer from my local windows to stream Twitter data I am getting this error:

Exception in thread "main" kafka.common.FailedToSendMessageException:
  Failed to send messages after 3 tries

Did I miss anything? I am able to telnet from my local system to the ec2 instance with 2181 and 9092 port. Do I need to configure public IP anywhere?
Note: the same producer and consumer code are running as expected in my local ubuntu VM, but getting above error when using aws ec2. I opened all the security groups ports.


text:
Q: How to create 32 bit version of Python code from 64 bit I created a 64 bit version of my python code using pyinstaller. However, I would like to create a 32 bit version. It seems like I would need to download a 32 bit version of python and redo my entire code in that version which seems like a lot of work. Is there no simple method of achieving my goal without having to redo everything?
Thanks

A: The code you actually have to run in 64 bit should work in a 32 bit environment. What you should make sure is that dependencies you are using in your code also work in 32 bit.


text:
Q: Как получить массив из другого сайта? Вот код который работает
var countries = JSON.parse(  Get("https://restcountries.eu/rest/v2/all?fields=name")); console.log(countries);

я хочу брать массив отсюда
https://gist.githubusercontent.com/Lwdthe1/81818d30d23f012628aac1cdf672627d/raw/45dc8bee7b4fc349ec87931100e0f258bb59f8ea/usaCities.js

У меня почему то не получается, в чём различия этих массивов кто может объяснить?

A: Как гласит MDN - js массив также валиден JSON, но:

*

*JSON требует двойных кавычек, которые будут использоваться вокруг строк и имен свойств. Одиночные кавычки недействительны.

*Даже одна неуместная запятая или двоеточие могут привести к сбою JSON-файла и не работать.
У Вас оба эти пункта в минусе. Кавычки одиночные и после последнего элемента массива стоит запятая

A: Проблема в том, что по второй ссылке - не JSON.
Для такого массива вам понадобится парсер, либо, если уверены в источнике, можно вычислить js массив с помощью eval:

const uri = 'https://gist.githubusercontent.com/Lwdthe1/81818d30d23f012628aac1cdf672627d/raw/45dc8bee7b4fc349ec87931100e0f258bb59f8ea/usaCities.js';

fetch(uri)
  .then(res => res.text())
  .then(res => eval(res))
  .then(list => console.log(list))

На самом деле, это не опаснее/не безопаснее, чем обычное подключение такого скрипта через <script>


text:
Q: How to pass viewpager instance to Adapter using an Interface class I have a an activity that holds many fragments. In each fragment i have a :
RecyclerView
Button
I can move from fragment to another using viewpager.
I am getting data from server and passing them to the adapter to populate the recyclerview as below :
adapter = new BrandsAdapter(getContext(), postArray,btValider,viewPager);

where postArray is a list of Strings.
BrandsAdapter.class :
 public BrandsAdapter(Context context, ArrayList<Brand> filteredItems,Button btValider,ViewPager viewPager) {
        this.context = context;
        this.filteredItems = filteredItems;
        this.btValider=btValider;
        this.viewPager=viewPager;

    }

onBindViewHolder
btValider.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                 .....
                 // Get user selected brands and move to another fragment
                    viewPager.setCurrentItem(3);

                }
            });

How can i create an Interface where i can add mybutton and viewpager instances so i don't pass them directly through BrandsAdapter because as we know from a memory point of view passing viewpager instance or other views through constructor can create cyclic dependencies and therefore memory leaks.

A: 1.Create an Interface,
public interface BtValiderClickListener {
void btValiderClick(int positon);
}

*Implement this interface

*Pass the instance of the interface to the adapter,
adapter = new BrandsAdapter(getContext(), postArray,btValider,this);

*In the adapter,
private BtValiderClickListener btValiderClickListener;

*then in your adapter constructor,
public BrandsAdapter(Context context, ArrayList<Brand> filteredItems,Button btValider,BtValiderClickListener btValiderClickListener) {
this.context = context;
this.filteredItems = filteredItems;
this.btValider=btValider;
this.btValiderClickListener=btValiderClickListener;
}

*In onBindViewHolder,
 btValider.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btValiderClickListener.btValiderClick(3)
        }
    });

*Override your method where you implemented interface,
   @Override
   public void btValiderClick(int positon) {
    viewPager.setCurrentItem(positon);
   }


text:
Q: ForkJoinPool stalls during invokeAll/join I try to use a ForkJoinPool  to parallelize my CPU intensive calculations.
My understanding of a ForkJoinPool is, that it continues to work as long as any task is available to be executed. Unfortunately I frequently observed worker threads idling/waiting, thus not all CPU are kept busy. Sometimes I even observed additional worker threads.
I did not expect this, as I strictly tried to use non blocking tasks.
My observation is very similar to those of ForkJoinPool seems to waste a thread.
After debugging a lot into ForkJoinPool I have a guess:
I used invokeAll() to distribute work over a list of subtasks. After invokeAll() finished to execute the first task itself it starts joining the other ones. This works fine, until the next task to join is on top of the executing queue. Unfortunately I submitted additional tasks asynchronously without joining them. I expected the ForkJoin framework to continue executing those task first and than turn back to joining any remaining tasks.
But it seems not to work this way. Instead the worker thread gets stalled calling wait() until the task waiting for gets ready (presumably executed by an other worker thread). I did not verify this, but it seems to be a general flaw of calling join().
ForkJoinPool provides an asyncMode, but this is a global parameter and can not be used for individual submissions. But I like to see my asynchronously forked tasks to be executed soon.
So, why does ForkJoinTask.doJoin() not simply executes any available task on top of its queue until it gets ready (either executed by itself or stolen by others)?

A: Since nobody else seems to understand my question I try to explain what I found after some nights of debugging:
The current implementation of ForkJoinTasks works well if all fork/join calls are strictly paired. Illustrating a fork by an opening bracket and join by a closing one a perfect binary fork join pattern may look like this:
{([][]) ([][])} {([][]) ([][])}
If you use invokeAll() you may also submit list of subtasks like this:
{([][][][]) ([][][][]) ([][][][])}
What I did however looks like this pattern:
{([) ([)} ... ]]
You may argue this looks ill or is a misuse of the fork-join framework. But the only constraint is, that the tasks completion dependencies are acyclic, else you may run into a deadlock. As long as my [] tasks are not dependent on the () tasks, I don't see any problem with it. The offending ]]'s just express that I do not wait for them explicitly; they may finish some day, it does not matter to me (at that point).
Indeed the current implementation is able to execute my interlocked tasks, but only by spawning additional helper threads which is quite inefficient.
The flaw seems to be the current implementation of join(): joining an ) expects to see its corresponding ( on top of its execution queue, but it finds a [ and is perplexed. Instead of simply executing [] to get rid of it, the current thread suspends (calling wait()) until someone else comes around to execute the unexpected task. This causes a drastic performance break down.
My primary intend was to put additional work onto the queue to prevent the worker thread from suspending if the queue runs empty. Unfortunately the opposite happens :-(

A: You are dead right about join(). I wrote this article two years ago that points out the problem with join().
As I said there, the framework cannot execute newly submitted requests until it finishes the earlier ones. And each WorkThread cannot steal until it's current request finishes which results in the wait().
The additional threads you see are "continuation threads." Since join() eventually issues a wait(), these threads are needed so the entire framework doesn't stall.

A: You're not using this framework for the very narrow purpose for which it was intended.
The framework started life as the experiment in the 2000 research paper. It's been modified since then but the basic design, fork-and-join on large arrays, remains the same. The basic purpose is to teach undergraduates how to walk down the leaves of a balanced tree. When people use it for other than simple array-processing weird things happen. What it is doing in Java7 is beyond me; which is the purpose of the article.
The problems only get worse in Java8. There it's the engine to drive all stream parallel work. Have a read in part two of that article. The lambda interest lists are filled with reports of thread stalls, stack overflow, and out of memory errors.
You use it at your own risk when you don't use it for pure recursive decomposition of large data structures. Even then, the excessive threads it creates can cause havoc. I'm not going to pursue this discussion any further.


text:
Q: Keeping shared keychain data private As Apple docs state, apps can share keychain data if they have the same App ID prefix and they've set the same keychain-access-groups in Entitlements.
However, I've been able to access shared keychain data from the app that has a different App ID prefix as long as I provide the proper keychain-access-groups as a hard-coded string. Like ABCDEFGHIJ.my.keychain.group.
It seems that keeping the keychain-access-groups value secret is the only thing that prevents someone from accessing the keychain data. Obviously, since it's just a plist value, this is not safe at all.
Is there any way to ensure that an app that is not included in my Apple Developer Program will not be able to access shared keychain, even if it knows my keychain-access-groups value?


text:
Q: Dolphin Mount ISO - Where does it go? With the latest version of Dolphin, you can right-click ISOs and select "Mount":

But it doesn't appear anywhere on the sidebar or in the device notifier. Does anywhere know where it goes so I can use it?
Thanks

A: Looks like this was a bug in an early release of the Dolphin ISO mounter. Now, mounted ISOs appear under Devices, or at /run/media/$USER/isoname:


text:
Q: Catalan divided by increasing powers Find the value of the converging sum $\frac{1}{k}+\frac{1}{k^2}+\frac{2}{k^3}+\frac{5}{k^4}+\frac{14}{k^5}+\frac{42}{k^6}+\frac{132}{k^7}...$,  where the numerators are the catalan numbers in sequence. Assume that $k \ge 4$.
I tried to use the recursion form, but it becomes extremely messy.
I also tried to find a short recursion to find the value to make it similar to the problem with the fibonacci #s instead of the catalan #s instead, but I can't seem to find such a recursion. Lastly, telescoping sums seem to not work, since it is hard to express each term as a difference of stuff.

A: Hint: the generating function of the Catalan sequence will give the answer. Check it out here:
http://en.wikipedia.org/wiki/Catalan_number


text:
Q: How can build a Binary Search Tree from an array of integers in C? I try to write a function which is used to build a BST from an array of integers. It takes 2 arguments: pointer to the array and the size of the array

*

*create the BST with successive inserts and return the pointer to the tree

*if size is 0, return NULL

sample;
int a[3] = {2,1,3};
return build(a, 3);

My work is here, but there is a problem in the recursion part, I cannot find my mistake, actually I know that I cannot use for loops correctly, but cannot solve.
In my code, firstly I changed format of array in an ascending order, then took the middle number, and made it root, then for left and right parts, I should do same things.
By the way, I have an insert function implementation, but I am not sure, can we need or use it in build function.
typedef struct TreeNode{
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
} TreeNode;

TreeNode* build(int *array, int size) {
    TreeNode *root = malloc(sizeof(TreeNode));
    int a,i,j;
    int mid = size/2;
    if(size==0)
        return NULL;
    else {
        for(i=0;i<size;i++) {
            for(j=i+1;j<size;j++) {
                if(array[i] > array[j]) {
                    a = array[i];
                    array[i] = array[j];
                    array[j] = a;
                }
            }
        }
        root->val = array[mid];
        for(i=0;i<mid;i++)
            root->left = build(array, mid);
        for(i=(mid+1);i<size;i++)
            root->right = build(array, mid);
        return root;
    }
}

A: Modify according to your concept:
#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode{
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
} TreeNode;

TreeNode* build(int *array, int size) {
    if(size == 0)
        return NULL;
    else {
        TreeNode *root = malloc(sizeof(TreeNode));//in the case of return NULL there is before if-block, cause of memory leak
        int i, j, mid;
        int swap = 1;

        j = size-1;
        while(swap){//To deter a repeat of the sort
            swap = 0;
            for(i = 0; i < j; ++i) {
                if(array[i] > array[i+1]) {
                    int temp = array[i];
                    array[i] = array[i+1];
                    array[i+1] = temp;
                    swap = 1;
                }
            }
            --j;
        }
        root->val = array[mid = size / 2];
        root->left  = build(array, mid);
        root->right = build(array + mid + 1, size - mid -1);
        return root;
    }
}

void print(TreeNode *p){
    if(p){
        print(p->left);
        printf("%d ", p->val);
        print(p->right);
    }
}

int main(void){
    //test
    int a[] = {1,5,9,2,6,4,8,3,7,0};
    TreeNode *root = build(a, 10);
    print(root);
    //deallocate
    return 0;
}


text:
Q: How to use a specific interface on a C# object in IronPython I have a C# class that implements 2 IEnumerable interfaces. How can I access either interface from IronPython?
My class:
public class MyClass : IEnumerable<TypeA>, IEnumerable<TypeB>
{
    IEnumerator<TypeA> IEnumerable<TypeA>.GetEnumerator()
    {
        return _lstTypeA.GetEnumerator();
    }

    IEnumerator<TypeB> IEnumerable<TypeB>.GetEnumerator()
    {
        return _lstTypeB.GetEnumerator();
    }
}

I tried the following in Python, but although it runs without errors it does not return any elements from the IEnumerable interface:
x = MyClass()
xA = clr.Convert(x, IEnumerable[TypeA])
for y in xA: print y

A: I don't like your class design. In particular that you implement two different versions of IEnumerable<T> that return different members. Two versions that return the same members is slightly better, but I still don't like that much.

*

*Implementing IEnumerable so it's consistent with both IEnumerable<T>s isn't possible here. In particular that breaks the OfType and Cast linq methods.

*You get overload resolution problems almost everywhere.  Methods like Select<T>(this IEnumerable<T> ...) don't know which IEnumerable to take.

*You can't use foreach on MyClass

*If both TypeA and TypeB are reference types the variance of IEnumerable<out T> comes back to bite you. Since both of them offer IEnumerable<T'> for all their common ancestors.

*It doesn't interact well with dynamically types languages

*A class being a two different collections at the same time rarely makes sense. It usually indicates that something went wrong in the mapping from concepts to classes.

*It's confusing and hard to understand. My intuition tells me it's evil and that I should burn it with fire :P

And Probably several more issues I didn't think of yet.

The work around is simple and clean: Have two separate enumerable properties.
public class MyClass
{
  public IEnumerable<TypeA> TypeAs{get{_lstTypeA.Select(x=>x)}};
  public IEnumerable<TypeB> TypeBs{get{_lstTypeB.Select(x=>x)}};
}

A: You need to call methods and properties as you were using reflection (that is actually what it happens under the hood).
In your case you should do:
x = MyClass()
enumerator = IEnumerable[TypeA].GetEnumerator(x)

then you can loop over enumerator:
for y in enumerator:
   print y

A: how i use specified interface

clr.AddReference('Platform.CardHost')
from Platform import CardHost
from Platform.CardHost import ICardHost

host = CardHost.CardHost.CreateInstance('session')
# ICardHost is interface
# inside C#
# public interface ICardHost {
# IExtensionManager ExtensionManager { get; }
em = ICardHost.ExtensionManager.__get__(host)


text:
Q: (sass):26096 How to fix 'Sass::SyntaxError: Invalid CSS after' error in Rails i am run this in local
rake assets:precompile --trace RAILS_ENV=production

ruby : 2.6.3
rails : 5.2.2
bundler : 2.0.2
puma : 3.12.1
this is my css
application.css
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */
*= require font-awesome.css
*= require bootstrap.css
*= require font-awesome.css
*= require lineicons.css
*= require mystyles.css
*= require styles.css
*= require weather-icons.css

error log
Sass::SyntaxError: Invalid CSS after "...ather-icons.css": expected "{", was ""
(sass):26096

i expect when running rake assets:precompile --trace RAILS_ENV=production is successfully

A: I think you should rename application.css to application.scss  and remove require tree and require self


text:
Q: Linq to Entity Paging With Large dataset too slow I'm analyzing player data over millions of matches from an online game.  I'm trying to page data into memory in chunks to reduce load times but using OrderBy with skip/take takes way too long (20+ minutes even for smaller queries).
This is my query:
var playerMatches = (from p in context.PlayerMatchEntities
                     join m in context.MatchEntities
                        on p.MatchId equals m.MatchId
                     where m.GameMode == (byte) gameMode
                        && m.LobbyType == (byte) lobbyType
                     select p)
                     .OrderBy(p => p.MatchId)
                     .Skip(page - 1 * pageSize)
                     .Take(pageSize)
                     .ToList();

MatchId is indexed.
Each match has 10 players, and I currently have 3.3 million matches w/ 33 million rows in the PlayerMatch table, but data is being collected constantly.
Is there a way to get around the large performance drop caused by OrderBy?
This post is similar but didn't seem to be resolved.
Edit:
This is the SQL query generated:
SELECT
`Project1`.`AccountId`,
`Project1`.`MatchId`,
`Project1`.`PlayerSlot`,
`Project1`.`HeroId`,
`Project1`.`Item_0`,
`Project1`.`Item_1`,
`Project1`.`Item_2`,
`Project1`.`Item_3`,
`Project1`.`Item_4`,
`Project1`.`Item_5`,
`Project1`.`Kills`,
`Project1`.`Deaths`,
`Project1`.`Assists`,
`Project1`.`LeaverStatus`,
`Project1`.`Gold`,
`Project1`.`GoldSpent`,
`Project1`.`LastHits`,
`Project1`.`Denies`,
`Project1`.`GoldPerMin`,
`Project1`.`XpPerMin`,
`Project1`.`Level`,
`Project1`.`HeroDamage`,
`Project1`.`TowerDamage`,
`Project1`.`HeroHealing`
FROM (SELECT
`Extent2`.`AccountId`,
`Extent2`.`MatchId`,
`Extent2`.`PlayerSlot`,
`Extent2`.`HeroId`,
`Extent2`.`Item_0`,
`Extent2`.`Item_1`,
`Extent2`.`Item_2`,
`Extent2`.`Item_3`,
`Extent2`.`Item_4`,
`Extent2`.`Item_5`,
`Extent2`.`Kills`,
`Extent2`.`Deaths`,
`Extent2`.`Assists`,
`Extent2`.`LeaverStatus`,
`Extent2`.`Gold`,
`Extent2`.`GoldSpent`,
`Extent2`.`LastHits`,
`Extent2`.`Denies`,
`Extent2`.`GoldPerMin`,
`Extent2`.`XpPerMin`,
`Extent2`.`Level`,
`Extent2`.`HeroDamage`,
`Extent2`.`TowerDamage`,
`Extent2`.`HeroHealing`
FROM `match` AS `Extent1` INNER JOIN `playermatch` AS `Extent2` ON `Extent1`.`MatchId` = `Extent2`.`MatchId`
 WHERE ((`Extent1`.`GameMode`) = 2) AND ((`Extent1`.`LobbyType`) = 7)) AS `Project1`
 ORDER BY
`Project1`.`MatchId` ASC LIMIT 0,1000

A: Another approach could be to have a VIEW that does the join and indexes the appropriate columns and then create a Table-Valued Function that uses the VIEW and returns a TABLE with only the page data.
You'll have to manually write the SQL query for the paging, but i think it would be faster.
I haven't tried something like that so i can't be sure there is gonna be a big speed boost.

A: You didn't include enough information to help you so I'll suggest.
One way to avoid order by is to store rows in a table already in the order. I suggest 'MatchId' is a primary key and a clustered index of MatchEntities. That means MatchEntities.MatchId is stored physically sorted. If you switch join streams to pull the sorted stream first and additive stream second you avoid expensive sorting.
Like this:
var playerMatches = (from m in context.MatchEntities     // note the switch: MatchEntities goes first
                 join p in context.PlayerMatchEntities
                    on p.MatchId equals m.MatchId
                 where m.GameMode == (byte) gameMode
                    && m.LobbyType == (byte) lobbyType
                 select p)
                 // .OrderBy(p => p.MatchId) // no need for this any more
                 .Skip(page - 1 * pageSize)
                 .Take(pageSize)
                 .ToList();

Also see a query plan to find out how the query is executed by the database, what type of join is being used, etc. Maybe your original query does not exploit sorting at all.


text:
Q: ScriptUi - Buttons not responsive with a palette After many attempts I managed to create a working custom progress bar, even if customizing it with the OnDraw command, it flickers (I still don't understand why, maybe it could be the continuous redraw with the update command).
I wanted to add a button that would stop the progress bar (then also the script), and maybe add a warning message, however I ran into a problem.
It seems that the buttons don't respond to clicks, either while the progress bar is advancing or on a normal palette.
On a dialog it works, on palette and window it doesn't.
I suspect it's because, to keep a palette open in photoshop, it has to be busy, otherwise it closes. This causes me to be unable to press the button.
I tried everything I could think of, but nothing worked.
There is a way to implement this?
Here is a sample of my code:
    progressbar (100);
    for ( var e = 0; e < 100; e++ ) {
        progressbar.progress ();
        }
    progressbar.close ();

    function progressbar (total) {
        var win = new Window ("palette", undefined, undefined, {closeButton: false, borderless: true});
        win.orientation = "row";
        var barheight = 15;
        var halfbarheight = barheight / 2;
        var barwidth = 500;
        var bar = win.add ("progressbar", [0, 0, barwidth, barheight], 0, total);
        bar.onDraw = function () {
            with (bar) {
                graphics.drawOSControl ();
                graphics.newPath ();
                graphics.moveTo (halfbarheight, 0);
                for (var a = 0; a < Math.PI; a += Math.PI / 100) {
                    graphics.lineTo ((-halfbarheight * Math.sin (a)) + halfbarheight, (-halfbarheight * Math.cos (a)) + halfbarheight);
                    }
                graphics.lineTo (halfbarheight + (bar.value * ((barwidth - barheight) / total)), barheight);
                for (var b = 0; b < Math.PI; b += Math.PI / 100) {
                    graphics.lineTo ((halfbarheight * Math.sin (b)) + halfbarheight + (bar.value * ((barwidth - barheight) / total)), (halfbarheight * Math.cos (b)) + halfbarheight);
                    }
                graphics.lineTo (halfbarheight, 0);
                graphics.closePath ();
                graphics.fillPath (graphics.newBrush (graphics.BrushType.SOLID_COLOR, [0.25, 0.83, 0.1]));
                }
            }
        var close = win.add ("iconbutton", [0, 0, 15, 15]);
        close.onDraw = function (event) {
            with (close) {
                graphics.drawOSControl ();
                graphics.ellipsePath (0, 0, size[0], size[1]);
                graphics.fillPath (graphics.newBrush (graphics.BrushType.SOLID_COLOR, [0.6, 0, 0]));
                if (event.mouseOver) {
                    graphics.fillPath (graphics.newBrush (graphics.BrushType.SOLID_COLOR, [0.85, 0, 0]));
                    }
                }
            }
        close.onClick = function () {
            progressbar.close ();
            return;
            }
        progressbar.close = function () {
            win.close ();
            }
        progressbar.progress = function () {
            bar.value++;
            $.sleep (100);
            win.update ();
            }
        win.show ();
        }

A: I'm not sure what you're trying to do. So, just in case, here is how I used to build a progressbar (with a text area and the button 'Cancel'):
var iterations = 10;

// show the progress bar
var bar = new Window('palette', 'Progress...');
var stat = bar.add('statictext', undefined, '');
stat.characters = 80;
var progressbar = bar.add('progressbar', [15,15,600,35], 0, iterations);

var bar_visible = true;
var button = bar.add('button', undefined, 'Cancel');
button.onClick = function() { bar.close(); bar_visible = false; }

bar.center();
bar.show();

var counter = 0;
for (var i=0; i<iterations; i++) {
    if (bar_visible == false) break;

    // update the progress bar
    counter++;
    progressbar.value = counter;
    stat.text = 'Processed ' + counter + ' from ' + iterations;
    bar.update();

    alert(counter); // <------- do stuff
}

// close the progress bar
bar.close();

Note: this example works fine on Windows, but on macOS the alert window blocks the button 'Cancel'. I used the alert window just to show the concept. Otherwise the 'Cancel' button works fine on macOS: it closes the palette and breaks the loop.


text:
Q: Template cast to super class I want to be able to pass functions with an object of class I as parameter, where I inherits from D, to FD constructor::
class D {}; class I: public D {};
FD(std::function<void(D*)> f): _f(f) {}

void test(I*) { std::cout << "Success" << std::endl; }
FD fd(test); fd.call();

As I have been researching I should implement a type conversion, but I do not know a clean way and did not find answers addressing type conversions appliable to my case.
Here is the full code:
#include <functional>
#include <iostream>

class D {}; class I: public D {};

class FD {
  protected:
    std::function<void(D*)> _f;
  public:
    explicit FD(std::function<void(D*)> f): _f(f) {}
    void call() { _f(0); }
};

void test(I*) { std::cout << "Success" << std::endl; }

int main () {
  FD fd(test); fd.call();
}

I get:
test.cpp: In function 'int main()':
test.cpp:17:13: error: no matching function for call to 'FD::FD(void (&)(I*))'
   FD fd(test); fd.call();
             ^
test.cpp:10:14: note: candidate: FD::FD(std::function<void(D*)>)
     explicit FD(std::function<void(D*)> f): _f(f) {}
              ^~
test.cpp:10:14: note:   no known conversion for argument 1 from 'void(I*)' to 'std::function<void(D*)>'

I have also tried using int and double:
#include <functional>
#include <iostream>

class FD {
  protected:
    std::function<void(double)> _f;
  public:
    explicit FD(std::function<void(double)> f): _f(f) {}
    void call() { _f(0); }
};

void test(int v) { std::cout << "Success" << std::endl; }

int main () {
  FD fd(test); fd.call();
}

With output:
Success

A: It's possible to explain the reason for the compilation error in excruciating technical detail, and why you cannot do what you want to do, in C++, but perhaps this fundamental reason will be clear to you if you consider a very simple thought experiment:
std::function<void(D*)> f;

You surely understand that this callable object can be called using a pointer to any subclass of D. You might have some other class called J that also inherits from D, and so this is perfectly acceptable:
class J : public D {};

J j;

f(&j);

But you are attempting to do here is construct your std::function using a pointer to a function that takes only I * as a parameter:
void test(I*)

If what you were attempting to do was possible, then this will mean that this test() function can be called, via the std::function<void (D*)> object, using a pointer to J, instead of I. Fail. This is, of course, is not allowed in C++. If the only relationship between two classes is that they all have the same parent class, you simply cannot convert a pointer to one of them to a pointer to the other one. C++ does not work this way.
And the reason why your 2nd example, with ints and doubles work, is because ints and doubles can be converted to each other. The same is not true with pointers to two random classes. A pointer to a class can be converted to a pointer to a different class only in certain, well-defined cases. What you want is not allowed in C++.
The only thing that can happen here is the test() function taking a D * as a parameter, crossing its fingers and attempting to dynamic_cast it to an I * (assuming that D meets the requirements for a dynamic-castable class). And then you will have to decide what happens when this conversion fails.

A: Of course, you can do the cast like this: FD fd(reinterpret_cast<void(*)(D*)>(test)); but this is UB.
The error is clear - you can't implicitly cast D* to I*. This violates polymorphism.
Are you sure you are not mixing up I and D?
UPD:
I assume downvoting this post means it is not clear. I will try to explain:
Imagine the following:
class D
{
public:
    void (*ok)() = +[] { std::cout << "OK"; };
};

class I: public D
{
public:
    void (*not_ok)() = ok;
};

ok() can be accesed from D instance while not_ok() cannot. Now you want to call your function taking pointer to I. But that means your function can call not_ok() which is not valid for pointer to D:
void test(I* i)
{
    i->ok();
    i->not_ok();
}

With raw pointers you can try this:
class FD {
  protected:
    std::function<void(D*)> _f;
  public:
    explicit FD(void(*f)(I*)) : _f(reinterpret_cast<void(*)(D*)>(f))
    {
    }
    void call() { _f(new I); }
};

It will print OKOK. But if you replacenew I with new D it will fail on not_ok() call
This is why C++ doesn't allow to implicitly cast pointers (while you still can implicitly cast int to double).
Even if you want to 'hack' your code, C++ has no global type conversion rules. Also, you can't get raw pointer from std::function, therefore, there is no way to do this.


text:
Q: My iterm2 can only use basic colors my iterm2 can only use basic colors.. I had tried the following 2 tricks but neither of them worked:

*

*set the "minimum contrast" to low

*set the report terminal type to "xterm-256color" (echo $TERM shows: xterm-256color)

any other suggestions? Thx

A: Download the solarized color scheme from Here
Import to your profile then Load Preset select dark background or light background.
I only have a basic color setup for command line prompts, see following picture.

If you want more fancy setups, have a look at this page Bash prompt
Or checkout Zsh schemes oh-my-zsh
Following is the section related to my command prompt in my .bash_profile file. I am also using Solarized color scheme for my iTerm2, keep that in mind.
  BLACK='\e[0;30m'
  BLUE='\e0;34m'
  BROWN='\e[0;33m'
  CYAN='\e[0;36m'
  DARKGRAY='\e[1;30m'
  GRAY='\e[0;37m'
  GREEN='\e[32m'
  LIGHTBLUE='\e[1;34m'
  LIGHTCYAN='\e[1;36m'
  LIGHTGRAY='\e[0;37m'
  LIGHTGREEN='\e[1;32m'
  LIGHTPURPLE='\e[1;35m'
  LIGHTRED='\e[1;31m'
  PURPLE='\e[0;35'
  RED='\e[0;31m'
  YELLOW='\e[1;33m'
  NC='\e[m'

  PS1="\`if [[ \$EUID -eq 0 ]]; then PCT='\[$LIGHTRED\]';
  else PCT='\[$LIGHTCYAN\]'; fi;
  echo '\[$NC\]['\$PCT'\u\[$YELLOW\]@\[$GREEN\]\h:\w\[$NC\]]\[$GRAY\] : \[$NC\]'\`"


text:
Q: Symfony assetic issue file does not exist I tried to resolve my problem all this morning but I didn't find the solution anywhere.
I have a Symfony project and I use Assetic for my css and js files.
Till today when I ran php bin/console assetic:dump --env=prod, it worked fine.
But now I have this error :

[Symfony\Component\Config\Exception\FileLocatorFileNotFoundException]
  The file "C:\wamp\www\PLIE08\app/config/config_=prod.yml" does not exist.

I don't understand why it adds = in my file.
Moreover, after running this command I realized that a folder called "=prod" is created in var/cache in addition to the dev and prod folder.
I tried to update, install composer, clear the cache, look in config file if something was wrong but I'm still blocked...
Somebody can tell me why it searchs the bad file ?
Thanks

A: try this command bin/console assetic:dump -e prod to verify duplicated =. Otherwise remove the entire content of the cache/prod folder, doest not clear:cache, remove all manually.


text:
Q: Access denied for user - (using password: NO) Hi I'm trying to connect to my database to use my registration form but im having no luck. When I run connection.php it displays the message: Access denied for user ''@'10.246.64.24' (using password: NO)
any tips much appreciated :)
connection.php:
<?php
$servername = "c3438525.co.uk.mysql";
$username = "c3438525_co_uk";
$password = "password";
ob_start();
$con=mysqli_connect("c3438525.co.uk.mysql", "c3438525_co_uk", "password", "c3438525_co_uk");

if ($con->connect_error)
{
    die("Connection failed: " . $con7>connect_error);
}
echo "Connected Successfully";
mysql_select_db( 'c3438525_co_uk' ) or die(mysql_error());
?>

and my registrationsubmit.php

<?php

include 'registrationform.php';
include 'connection.php';
?>

<?php
if (isset($_POST['regsubmit'])) {
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $username = $_POST['username'];
    $password = $_POST['password'];
    //Insert into database the values entered in the registration form.
    $query = "INSERT INTO users (FirstName, LastName, Username, Password) VALUES ("$firstname","$lastname", "$username", "$password")"
}
  Echo "Registration Successful - Press the Home button to return to the homepage.";

}
?>

A: mysqli_connect(...
mysql_select_db('c3438525_co_uk'

You're mixing mysqli with functions from the old mysql extension. That doesn't work.
Since there has been no connection established via mysql_connect, the mysql extension tries to establish the default connect when mysql_select_db is called. Hence the user ''@'10.246.64.24' (using password: NO) message.
Remove all mysql_* functions and use only the mysqli versions.
Btw: in your second script (as posted) the query is not actually sent to the mysql server. But it's probably not the "real" script anyway, since it would cause a parse error because of the double-quotes within the dobule-quoted string literal.
But while you're at it, please also have a read of http://docs.php.net/security.database.sql-injection


text:
Q: CMD.EXE batch script to display last 10 lines from a txt file Any ideas how to echo or type the last 10 lines of a txt file?
I'm running a server change log script to prompt admins to state what they're doing, so we can track changes. I'm trying to get the script to show the last 10 entries or so to give an idea of what's been happening recently. I've found a script that deals with the last line, as shown below, but can't figure out what to change in it to display the last 10 lines.
Script:
@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (c:\log09.txt) do (
set var=%%a
)
echo !var!

Example of log file:
06/02/2009, 12:22,Remote=Workstation-9,Local=,
mdb,bouncing box after updates,CAS-08754,
=================
07/02/2009, 2:38,Remote=,Local=SERVER1,
mdb,just finished ghosting c drive,CAS-08776,
=================
07/02/2009, 3:09,Remote=,Local=SERVER1,
mdb,audit of server,CAS-08776,

Any thoughts?
The script works great, just need it to pipe more lines to the screen.

A: There are several windows implementations of the tail command. It should be exactly what you want.
This one sounds particularly good:
http://malektips.com/xp_dos_0001.html
They range from real-time monitoring to the last x lines of the file.
Edit: I noticed that the included link is to a package It should work, but here are some more versions:
http://www.lostinthebox.com/viewtopic.php?f=5&t=3801
http://sourceforge.net/projects/tailforwin32

A: If file is too large it can take too long to get count of lines
another way is to use find and pass it a nowhere string
$find /v /c "%%$%!" yourtextfile.txt

this would result an output like this
$---------- yourtextfile.txt: 140

then you can parse output using for like this
$for /f "tokens=3" %i in ('find /v /c "%%$%!" tt.txt') do set countoflines=%i

then you can substract ten lines from the total lines

A: After trying all of the answers I found on this page none of them worked on my file with 15539 lines.
However I found the answer here to work great. Copied into this post for convenience.
@echo off
for /f %%i in ('find /v /c "" ^< C:\path\to\textfile.txt') do set /a lines=%%i
set /a startLine=%lines% - 10
more /e +%startLine% C:\path\to\textfile.txt

This code will print the last 10 lines in the "C:\path\to\textfile.txt" file.
Credit goes to OP @Peter Mortensen

A: using a single powershell command:
powershell -nologo "& "Get-Content -Path c:\logFile.log -Tail 10"

applies to powershell 3.0 and newer

A: Hopefully this will save Joel's eyes :)
@echo OFF

:: Get the number of lines in the file
set LINES=0
for /f "delims==" %%I in (data.txt) do (
    set /a LINES=LINES+1
)

:: Print the last 10 lines (suggestion to use more courtsey of dmityugov)
set /a LINES=LINES-10
more +%LINES% < data.txt

A: This answer combines the best features of already existing answers, and adds a few twists.
The solution is a simple batch implementation of the tail command.
The first argument is the file name (possibly with path information - be sure to enclose in quotes if any portion of path contains spaces or other problematic characters).
The second argument is the number of lines to print.
Finally any of the standard MORE options can be appended: /E /C /P /S /Tn. (See MORE /? for more information).
Additionally the /N (no pause) option can be specified to cause the output to be printed continuosly without pausing.
The solution first uses FIND to quickly count the number of lines. The file is passed in via redirected input instead of using a filename argument in order to eliminate the printout of the filename in the FIND output.
The number of lines to skip is computed with SET /A, but then it resets the number to 0 if it is less than 0.
Finally uses MORE to print out the desired lines after skipping the unwanted lines. MORE will pause after each screen's worth of lines unless the output is redirected to a file or piped to another command. The /N option avoids the pauses by piping the MORE output to FINDSTR with a regex that matches all lines. It is important to use FINDSTR instead of FIND because FIND can truncate long lines.
:: tail.bat File Num [/N|/E|/C|/P|/S|/Tn]...
::
::   Prints the last Num lines of text file File.
::
::   The output will pause after filling the screen unless the /N option
::   is specified
::
::   The standard MORE options /E /C /P /S /Tn can be specified.
::   See MORE /? for more information
::
@echo OFF
setlocal
set file=%1
set "cnt=%~2"
shift /1
shift /1
set "options="
set "noPause="
:parseOptions
if "%~1" neq "" (
  if /i "%~1" equ "/N" (set noPause=^| findstr "^") else set options=%options% %~1
  shift /1
  goto :parseOptions
)
for /f %%N in ('find /c /v "" ^<%file%') do set skip=%%N
set /a "skip-=%cnt%"
if %skip% lss 0 set skip=0
more +%skip% %options% %file% %noPause%

A: You should probably just find a good implementation of tail. But if you really really insist on using CMD batch files and want to run on any NT machine unmolested, this will work:
@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (c:\tmp\foo.txt) do (
set var9=!var8!
set var8=!var7!
set var7=!var6!
set var6=!var5!
set var5=!var4!
set var4=!var3!
set var3=!var2!
set var2=!var1!
set var1=!var!
set var=%%a
)
echo !var9!
echo !var8!
echo !var7!
echo !var6!
echo !var5!
echo !var4!
echo !var3!
echo !var2!
echo !var1!
echo !var!

A: I agree with "You should use TAIL" answer. But it does not come by default on Windows. I suggest you download the "Windows 2003 Resource Kit" It works on XP/W2003 and more.
If you don't want to install on your server, you can install the resource kit on another machine and copy only TAIL.EXE to your server. Usage is sooooo much easier.
C:\> TAIL -10 myfile.txt

A: Here's a utility written in pure batch that can show a lines of file within a given range.To show the last lines use (here the script is named tailhead.bat):
call tailhead.bat -file "file.txt" -begin -10

A:
Any ideas how to echo or type the last
  10 lines of a txt file?

The following 3-liner script will list the last n lines from input file. n and file name/path are passed as input arguments.
# Script last.txt
var str file, content ; var int n, count
cat $file > $content ; set count = { len -e $content } - $n
stex -e ("["+makestr(int($count))) $content

The script is in biterscripting. To use, download biterscripting from http://www.biterscripting.com , save this script as C:\Scripts\last.txt, start biterscripting, enter the following command.
script last.txt file("c:\log09.txt") n(10)

The above will list last 10 lines from file c:\log09.txt. To list last 20 lines from the same file, use the following command.
script last.txt file("c:\log09.txt") n(20)

To list last 30 lines from a different file C:\folder1\somefile.log, use the following command.
script last.txt file("C:\folder1\somefile.log") n(30)

I wrote the script in a fairly generic way, so it can be used in various ways. Feel free to translate into another scripting/batch language.


text:
Q: Combining 3 tables in a sql query - Error column name is ambiguous I am trying to combine 3 tables in one query with MySQL. However, I'm getting an error saying that the column name is ambiguous.
gndsale.AMOUNT is a column from another table named gndsale and the word AMOUNT is from gndtndr.
Error: Column 'amount' in field list is ambiguous
Here is my code:
SELECT g.ID
     , concat(emp.FIRSTNAME, ' ', emp.LASTNAME) Fullname
     , FORMAT(ROUND(SUM(s.AMOUNT), 2),0) as DECLARED
     , FORMAT(ROUND(SUM(amount), 2),0) as CALCULATED
     , `DATE`
     , `CHECK`
  FROM gndtndr g
  JOIN emp
    ON emp.ID = g.ID
  JOIN gndsale s
    on g.ID= S.ID
 group
    by EMPLOYEE

A: Why don`t you use ROUND(SUM(gndtndr.AMOUNT), 2),0)


text:
Q: Counting the number of bit strings containing a substring Consider a general bit string of length $n$; how many bit strings are there that contain a substring $T$?
For example, given a bit string of length 6, how many are there that contain $110$ as a substring, and how many that contain $101$?

A: Given the comments, I think you should check the article here : https://oeis.org/A005251 in OEIS.
The mentioned recurrence formula is : a(n) = a(n-1) + a(n-2) + a(n-4)  and it may be obtained by taking into account four kind of sequences:
$A_n$ : good sequences of length n that finish in 00
$B_n$ : good sequences of length n that finish in 01
$C_n$ : good sequences of length n that finish in 10
$D_n$ : good sequences of length n that finish in 11
and see what happens if we add one digit.
their sum $E_{n+1}$ would be expressed  :
$$E_{n+1} =  A_{n+1} + B_{n+1}+C_{n+1}+D_{n+1} = (A_n+B_n+C_n+D_n)  + A_{n-1} + B_{n-1}  + D_{n-1} = ....... =E_n + E_{n-1} + E_{n-3}$$
where the first four E's are 4, 7, 12, 21 for n = 2, 3, 4, 5 and they have to be obtained by hand.

A: Again, given the work around strings in the last days, there is a simple method to obtain a GF for the strings avoiding 110.
Suppose that we generate strings in the language $L = (1+0+110)^*$. There are two ways of obtaining the bad 110 in the process of building strings.
$\alpha = \ $ the hard way, by adding 0's and 1' to some previous string
$\beta = \ $ the short way, by adding directly a 110 to some previous string
for example, a string that contains two occurrences of 110 (there are no overlappings)
$w = ....110...110...$ may be obtained in four ways, depending on what method was used to derive each 110.
We have a multiplicity of 4 for $w$.
If we use a $-$ sign in the expression $(x+y-xxy)$ , the coefficient of the algebraic sum that describes the multiplicity of w changes from $4$ to $0$, because $1-1-1+1=0$. The four cases are  $\alpha\alpha,\alpha\beta, \beta\alpha,\beta\beta $ where $\alpha\alpha$ means that the two $110's$ of $w$ were obtained the hard way.
So happens for other strings with multiplicities of 8, 16, 32...
It remains to write the GF
$1+(x+y-xxy)+(x+y-xxy)^2+... = \frac{1}{1 -x - y + xxy}$
We have obtained https://oeis.org/A000071, the Fibonacci numbers - 1 in OEIS.


text:
Q: Shared Ip Hosting i am a newbie in the field so i need sm1 to enlight me with authentic knowledge.thanks in advance.
for example
ns1.bh-17.webhostbox.net
this above nameserver shows various domains that make use of it to resolve to correct host.
so my question is ->suppose some abc.com  uses above nameserver given by hosting provider to bind domain ,
1. what is or how to find  actual ip adress of machine hosting abc.com that have all actual website files?

*does this ip address is some local lan ip identifying particular machine having abc.com website files or this ip is exposed to internet so any can access it straightaway just typing in the browser from anywhere?

A: A hosting company can have multiple domains living at the same IP, or various IPs living on the same server.
There are a variety of tools to figure out what domains reside on a given IP address, but access to these is still protected by the hosting company. So to answer:
1: You can get this from your webhost, or search who.is to see what IP a domain resides on.
2: The Ip is exposed, in that you can type it and (along with the username) view the website, but that isn't really identifying the 'machine' so much, as the IP can be moved from one server to another. It really just let's you view the site normally.
I hope that helps...


text:
Q: How to transfer linebreaks from a multiline textbox to a sql database and and then enforce them in a gridview label? I am trying to enter text into a multiline textbox that then gets transferred across into a SQL Server database and then retrieved from said database and displayed within a label in a gridview. So far this is my code on the label
<asp:Label ID="NationalProjectDescriptionLabel" `CssClass="bodyText" runat="server" Text='<%# Eval("NationalProjectDescription").ToString().Replace(System.Environment.NewLine, "<br />") %>' />`

However it the linebreaks that are entered in the textbox do not appear to be copying across into the database, to begin with.
This is my code for transferring to the database
public static String createNewNationalProject(string strTitle, string strDescription)
{
SqlConnection conn = openConnection();//Open Connection

string strSQL = "INSERT INTO NationalProject(NationalProjectTitle, " +
            " NationalProjectDescription) " +
            " VALUES('" + strTitle + "', '" + strDescription + "')";//Insert Into Statement

SqlCommand cmd = new SqlCommand(strSQL, conn);//Close Connection

cmd.ExecuteNonQuery();

closeConnection(conn);
return strTitle;//Display Success

Any help would be greatly appreciated

A: On the way into the database, if I know I want the data back to be displayed on a label so it looks as though there is a carriage return between each row, I store it using replace
REPLACE(@YourString, CHAR(10) + CHAR(13), '<br />')

Works for me. Or you can do the replace on the way out of the database. Whichever you fancy.
Just an aside, do yourself a favour and pass your data to a stored procedure using command parameters. Code is treated as a text literal, so SQL Injection is not a concern. Why people write SQL code in the front end baffles me.


text:
Q: YouTube Data API OAuth 2.0 - response scope parameter throws 403 I'm requesting an OAuth code for YouTube authorization / refresh tokens.  My request is valid and so is YouTube's API response; HOWEVER, their response includes a 'scope' argument at the end that throws a 403.  Since they want a full URL as the scope parameter and they pass it back in the redirect as a full URL, it throws a 403 and I cannot extract the code parameter from the URL.  Example redirect from their own docs (https://developers.google.com/youtube/v3/guides/auth/server-side-web-apps):
...oauth2callback?state=state_parameter_passthrough_value&code=4/tQEJXSR8oWUlGNinu2ewAaCxEKknh_2zTm9g9Wa-mIPJK85mkaipYczZR35_t2XfqP806TspR0FLUFcIQ4sb_-Q&scope=https://www.googleapis.com/auth/drive.metadata.readonly

YouTube controls the redirect URL, and their addition of this scope argument at the end causes a 403.  Remove the scope argument, it works perfectly.  Anyone know a workaround for this / am I missing something?

A: Fixed.
For anyone running into this, security settings on our server were blocking any requests containing args starting with 'http/s://' See rules related to remote file injection in your security settings.


text:
Q: Programmatic access to Brother ADS-1000W I've got a Brother ADS-1000W receipt scanner and using the ControlCenter4 software it works great. However I would like to be able automate the scanning process and I can't find any pointers/clues on where to get access to the ADS-1000W specific features. With the ControlCenter4 software, I can have the scanner deskew images. It also scans to an arbitrary length and width (matching the scanned receipt). I'm assuming this is being handled by the scanner, but it may be happening in the ControlCenter4 software. These features specifically don't seem to be accessible in the TWAIN interface. I tried using TWAINCommander 3 and it doesn't show the deskew and arbitrary size features in the TWAIN interface.
I've got both Linux and Windows machines available and I'm cool with a commandline solution or an SDK that I have to write software to implement. If it's an SDK, I prefer Python.
I know this is somewhat open-ended, but hoping someone can point in a direction for further research.

A: Just in case anyone else stumbles across this question: The ADS-1000W supports scanning to FTP. If PDF is selected, then the scanner supports the de-skew option, so I installed vsftpd on my linux box and used Python to process the files as their uploaded.


text:
Q: How To Check if locally created ID does not exist in Firestore database, if it does, regerate ID and try again until Document doesn't alreadt exist I am trying to create a unique identifier for a document in a Firestore database. This id is a session ID that needs to be unique, locally generated and not loads of characters long (like the automatically generated one). I am trying to write code that checks to see if the document with that ID already exists. If it does not then set the SessionID, if it does exist then randomly generate another ID and perform the check again. This should loop continue until no document exists with that ID and then the session can initialize. The issue is that I can't put this in a while loop as Firebase connectivity cannot handle this. Does anyone have any suggestions, or another way to achieve the same thing? Thank you in advance.
func setsessionid () {

        sessionid = randomAlphaNumericString(length: 6)

        let docRef = self.db.collection("strokedata").document(self.sessionid!)

        docRef.getDocument { (document, error) in
            if let document = document, document.exists {

            } else {

                let currentsession = self.sessionid!
                self.sessionID.text = "SESSION ID: \(currentsession)"

                let user = Auth.auth().currentUser
                if let user = user {
                        self.userid = user.uid
                }

                print("Document does not exist")

            }
    }


text:
Q: How to prevent an element from ever sticking out of screen? Say there are some "absolutely positioned" elements whose coordinates(unit: %) are grabbed with Ajax.
Sometimes a certain edge of them sticks out of the screen, like when they are too right or too top. I cannot position them as right: 0 because their parent element is already "absolutely positioned", hence that won't work.
How can one prevent an element from ever sticking out of screen, given its direct parent element is not the document.body?

A: Have you tried using the css property overflow: hidden on the body? For example:

.box {
  border: 1px solid #222;
  width: 300px;
  height: 300px;
  overflow-y: hidden;
  overflow-x: scroll;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae suscipit, autem magnam ab. Possimus perferendis officiis doloremque impedit quia quos labore optio quas cum incidunt. Blanditiis dicta, sunt numquam quos.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae suscipit, autem magnam ab. Possimus perferendis officiis doloremque impedit quia quos labore optio quas cum incidunt. Blanditiis dicta, sunt numquam quos.

If you want content to never move out of range of the body, you'd need to grab that element's position relative to the window and not allow it to move beyond its borders (for example, any given element's left position relative to the body shall never be more than windowWidth-currentElementWidth). You can find more on this here


text:
Q: Prove that if $a,b,c>0$ then ${1\over a}+{1\over b}+{1\over c}\ge{2\over a+b}+{2\over b+c}+{2\over c+a}$
Prove that if $a,b,c>0$ then ${1\over a}+{1\over b}+{1\over c}\ge{2\over a+b}+{2\over b+c}+{2\over c+a}$

Excuse me but I am new to inequalities and have been practicing some questions including the one above. The one above looks easy but for me is not. I tried to use AM-GM-HM but led to even greater problems. Here is my attempt:
$${a+b+c\over3}\ge{3\over{1\over a}+{1\over b}+{1\over c}}$$
$${1\over 2}\biggl({(a+b)+(b+c)+(c+a)\over3}\biggr)\ge{3\over{1\over a}+{1\over b}+{1\over c}}$$
$$\iff {{1\over a}+{1\over b}+{1\over c}\over3}\ge\Biggl({1\over{6\over a+b}+{6\over b+c}+{6\over c+a}}\Biggr)$$
I could barely spot the wanted up there but cannot continue further.
I also got that
$${2\over a+b}+{2\over b+c}+{2\over c+a}\ge{1\over a+b+c}$$
Any help, if maybe a different method, would be appreciated. Thank you in advance.

A: We apply the arithmetic-harmonic mean inequality in variables $a,b$:
$$\frac{1}{2}\left(\frac{1}{a}+\frac{1}{b}\right)\ge \frac{2}{1/(1/a)+1/(1/b)}=\frac{2}{a+b}$$
Now do this twice more: in variables $a,c$, and in variables $b,c$.  Then add the three inequalities.


text:
Q: Selecting items in a QTreeView with keyboard arrows I'm trying to select an item in my QTreeView with the arrow keys but cannot find a method belonging to this class that returns the index of the highlighted item.
Up to now, i have only been able to select item with a click of the mouse :
connect(m_QTreeView, SIGNAL(clicked(QModelIndex)), this, SLOT(ItemTreeClicked(QModelIndex)));

but if I try to then change the focus with the keyboard arrows the current index is not updated.
To be honest, even my "mouse click" version isn't perfect because i have had use a Boolean that is initialized to false and passes to true when I enter the slot ItemTreeClicked. I had to do this because when i try to delete an item from the list, if I haven't clicked anything yet my app crashes.
I am coding in c++ on QtCreator 4.7.4
Any help or example code would be greatly appreciated.
Cheers.

A: Maybe you could subclass QTreeView and override the keyPressEvent method so it changes the current index?
myqtreeview::keyPressEvent(QKeyEvent* event){

    QModelIndex qmi = this->currentIndex();

    if(event->key() == Qt::Key_Down){
        this->setCurrentIndex(QAbstractItemModel::createIndex(qmi->row()+1, qmi->column()));
    }else{
        ...
    }
    QTreeView::keyPressEvent(event);
}

Note: This is just an idea, I can't test it at the moment so you probably have to adjust this a bit if you want to try it out


text:
Q: IntelliSense for Enum in Custom Configuration Section I want to use an enum in my Custom Configuration Section. So I implemented an enum DatabaseMode and the according property.
I also implemented the according Property in my System.Configuration.ConfigurationElement. But for the IntelliSense to work in the web.config I need to provide the schema definition (xsd) mirroring the same structure in xsd format.
My question is how the schema is supposed to look to support the enum?
The enum with the different options:
public enum DatabaseMode
{
   Development,
   Deployment,
   Production
}

The property storing the information about the Mode:
[ConfigurationProperty(databaseAlias)]
public DatabaseElement Database
{
   get { return (DatabaseElement)this[databaseAlias]; }
   set { this[databaseAlias] = value; }
}

Below the important part of my schema file:
<xs:element name="database">
  <xs:complexType>
    <xs:attribute name="server" type="xs:anyURI" use="required" />
    <xs:attribute name="name" type="xs:string" use="required" />
    <xs:attribute name="user" type="xs:string" use="required" />
    <xs:attribute name="password" type="xs:string" use="required" />
  </xs:complexType>
</xs:element>

A: You can actually define an enumeration in XSD's. For your example DatabaseMode property, the XSD fragment will look like this:
<xs:attribute name="databaseMode"> <!-- I'm assuming you're using camelCasing -->
    <xs:simpleType>
        <xs:restriction base="xs:string">
            <xs:enumeration value="development" />
            <xs:enumeration value="deployment" />
            <xs:enumeration value="production" />
        </xs:restriction>
    </xs:simpleType>
</xs:attribute>

Hope that helps.
A rleated question, in case anyone else wants to answer is, once the XSD is created, where should it be placed so that Visual Studio recognizes it within the web.config file?
UPDATE: I found the answer to my above question here on SO.


text:
Q: How to upload my custom Jenkins Plugin to a Jenkins Server using a Python Script I need to test my custom Jenkins Plug-in my-plugin.hpi to a set of Jenkins Servers.
How best can I do it using say a Python Script?

A: Following Python script uses requests module and Jenkins HTTP APIs to perform the same.
import requests
ciUrl = 'https://jenkins-server-url/my-ci-name'
files = {'file': open('my-plugin.hpi', 'rb')}
headers = {'Authorization':'Basic <base-64-encodeder-username-password>'}
### Uploading the HPI plugin file
r = requests.post(ciUrl + "/pluginManager/uploadPlugin", files=files, headers=headers, verify=False)
### Safe Restart the Jenkins to ensure plugin is installed.
r = requests.post(ciUrl + "/safeRestart", headers=headers, verify=False)

print(r.text)

NOTE
  verify=False ensure SSL Validation is turned off. If you are accessing an-unknown Jenkins server, please set verify=True.


text:
Q: Modify SipAddress Programmatically I know how to add/edit email address in a contact programmatically, but i don't know how to retrieve/modify SIP_address/Internet_call in a contact,I've read many documentation based on it, including  Modifying contact information. Please help me to implement this

A: Changing the Sip Address is exactly the same as changing a contact's e-mail address. Just use ContactsContract.CommonDataKinds.SipAddress instead ofContactsContract.CommonDataKinds.Email.
A small pre-coffee example:
import java.util.ArrayList;
import android.content.ContentProviderOperation;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.SipAddress;
//[...]
private String mSipAddress = "cecin\'estpasunesipaddress";
//[...]
    try {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
           .withSelection(Data.RAW_CONTACT_ID + " = ?", new String[] {mRawContactId})
           .withSelection(Data._ID + " = ?", new String[] {mDataId})
           .withValue(Data.MIMETYPE, SipAddress.CONTENT_ITEM_TYPE)
           .withValue(Data.DATA1, mSipAddress)
           .withValue(SipAddress.TYPE, SipAddress.TYPE_HOME)
           .build());
        getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
//[...]

See this GitHub repository for an example on how to get the fields that are not declared here. I got it from this answer. Relevant documentation.


text:
Q: Insufficient Permission: Request had insufficient authentication scopes error in App Script with proper scopes calling Directory API I have an App Script project on a Google Sheet. The App Script function is triggered using the onFormSubmit function, so when a user submits a Google form, it gets added to the sheet, and ideally an email is sent. I wanted to perform a check of the email address and look up the user's name from their email address to make the message look nicer.
However, every time I try to call the Directory API I get the following error:
GoogleJsonResponseException: API call to directory.users.get failed with error: Insufficient Permission: Request had insufficient authentication scopes.
    at sendFormByEmail(Code:33:35)
As I had the Directory API enabled under Advanced Serivces already I created a new .gs file to test. It worked fine. The exact same line of code in test.gs fails when run in project.gs, and I don't understand why.
Code snippet:
function sendFormByEmail(e)
{
  // Remember to replace this email address with your own email address
  var email = "myemail@company.com";

  // load spreadsheet where results were added and init default vars
  var s = SpreadsheetApp.getActiveSheet();
  var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
  var message = "";
  var subject = "";
  var term_obj =
      {
        timestamp: 0,
        //object creation
      };

  // The variable e holds all the form values in an array.
  term_obj.timestamp = e.namedValues[headers[0]].toString();
  term_obj.termed_user = e.namedValues[headers[2]].toString();
  //more assignments

  // verify the user exists
  Logger.log("Termed user is: " + term_obj.termed_user);
  Logger.log(AdminDirectory.Users.get(term_obj.termed_user));

It also fails when I insert a static string of a user I know is valid.
https://www.googleapis.com/auth/admin.directory.user.readonly is listed in the scopes. Admin Directory API is enabled.
What's happening?

A: I found my mistake - I had created the trigger on my non-admin account. I had to delete that formsubmit trigger and then re-create it on my superadmin account.


text:
Q: Eliminar registros tipo datetime de una tabla de usuarios Estoy haciendo una aplicación web que toma datos de un lector de huellas. Importo todos los registros a la BD de xampp y hasta ahí todo bien.
Cuando quiero evaluar las asistencias me encuentro con que hay 2 entradas.
Por ejemplo una es: 2018-03-05 08:50:30 y la otra 2018-03-05 08:50:52. Esto pasa cuando ponen el dedo en el lector 2 veces.. Como puedo hacer para eliminar estos registros?
7,Enzo Rodriguez ,2018-02-22 17:34:28
7,Enzo Rodriguez ,2018-02-22 17:34:31

id,Nombre,fechaYHora(Datetime)


text:
Q: Alternate of WHMCS Alright, I know there might have lots of answers for that but I need some real suggestion on which I can depend. Can anyone please suggest me a free script for billing which is stable, user-friendly and have maximum features?
Thank you so much in advance!

A: Check HostBill. It can be used for billing and managing your servers.

A: While free is nice, I still would definitely recommend going with WHMCS to manage your billing/clients
While these are free and opensource, I really wouldn't recommend them. They're pretty basic. Trust me, it's worth paying for a license for WHMCS instead
TheHostingTool
ShineISP
Test them carefuly

A: I've been using WHMCS for years. Its the best. And you can get a FREE license with many hosting providers (Namhost.com being one i know of). They also offer a free license for WHM Autopilot on certain packages.
But your other options are:

*

*ClientExec (not free, but only 12 USD)

*WHM Autopilot (not free, but only 15USD)

*Box Billing (free)

A: WHMCS is no more working in UBUNTU 14.04 or any other surrounding using PHP 5.5 and they wrote that it might take months until they release first betas!!!
he people from ioncube wrote:

we cannot offer a solution at this time ... Again, this is not a
  deliberate restriction, but rather a result of PHP's tremendous
  changes in their execution engine. For now the only fix for you
  appears to be to downgrade for PHP 5.4.

And WHMCS wrote

Exactly, so as of our next major release we will no longer be
  supporting PHP 5.2 so that we can encode using the version of Ioncube
  which supports PHP 5.3 and above. The current version of WHMCS still
  supports PHP 5.2, so at this time it isn't possible for us to
  distribute a single copy which supports 5.2 and 5.5+.

and

I can advise that we will not be releasing v6.0 this weekend, a beta
  is expected in the next few months.

better use another solution before loosing your customers ;-)


text:
Q: Why is the performance of BufferedReader so much worse than BufferedInputStream? I understand that using a BufferedReader (wrapping a FileReader) is going to be significantly slower than using a BufferedInputStream (wrapping a FileInputStream), because the raw bytes have to be converted to characters. But I don't understand why it is so much slower! Here are the two code samples that I'm using:
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filename));
try {
  byte[] byteBuffer = new byte[bufferSize];
  int numberOfBytes;
  do {
    numberOfBytes = inputStream.read(byteBuffer, 0, bufferSize);
  } while (numberOfBytes >= 0);
}
finally {
  inputStream.close();
}

and:
BufferedReader reader = new BufferedReader(new FileReader(filename), bufferSize);
try {
  char[] charBuffer = new char[bufferSize];
  int numberOfChars;
  do {
    numberOfChars = reader.read(charBuffer, 0, bufferSize);
  } while (numberOfChars >= 0);
}
finally {
  reader.close();
}

I've tried tests using various buffer sizes, all with a 150 megabyte file. Here are the results (buffer size is in bytes; times are in milliseconds):
Buffer   Input
  Size  Stream  Reader
 4,096    145     497
 8,192    125     465
16,384     95     515
32,768     74     506
65,536     64     531

As can be seen, the fastest time for the BufferedInputStream (64 ms) is seven times faster than the fastest time for the BufferedReader (465 ms). As I stated above, I don't have an issue with a significant difference; but this much difference just seems unreasonable.
My question is: does anyone have a suggestion for how to improve the performance of the BufferedReader, or an alternative mechanism?

A: in BufferedReader implementation there is a fixed constant defaultExpectedLineLength = 80, which is used in readLine method when allocating StringBuffer. If you have big file with lots of lines longer then 80, this fragment might be something that can be improved
if (s == null)
    s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);

A: The BufferedReader has convert the bytes into chars.  This byte by byte parsing and copy to a larger type is expensive relative to a straight copy of blocks of data.
byte[] bytes = new byte[150 * 1024 * 1024];
Arrays.fill(bytes, (byte) '\n');

for (int i = 0; i < 10; i++) {
    long start = System.nanoTime();
    StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes));
    long time = System.nanoTime() - start;
    System.out.printf("Time to decode %,d MB was %,d ms%n",
            bytes.length / 1024 / 1024, time / 1000000);
}

prints
Time to decode 150 MB was 226 ms
Time to decode 150 MB was 167 ms

NOTE: Having to do this intermixed with system calls can slow down both operations (as system calls can disturb the cache)


text:
Q: Dequeue is not working when consumer is dead I have a queue propagation form source_queue to dest_queue@dblink the payload is an anydata. A subscriber is added to source_queue:
sys.aq$_agent('CONSUMER', dest_queue@dblink, null);

Now I wanted to know if there is a way to use dbms_aq.dequeue at source_queue if the enqueued message could not be propagated, because the network to dest_queue@dblink goes down for a while. I tried it with the following:
m_queueOpts.consumer_name := 'CONSUMER';
m_queueOpts.dequeue_mode := dbms_aq.remove;

DBMS_aq.dequeue (
queue_name => 'source_queue',
dequeue_options => m_queueOpts,
message_properties => m_msgProps,
payload => m_data,
msgid => m_msgId
);

but I got an error:ORA-25247: CONSUMER is not a recipient of specified message
which is right, because the reciepient is on dest_queue@dblink.
but I want to dequeue or remove the message from source_queue if they could not propagated. Is there a other way of dequeueing from source_queue?
I tried it, to set a message_id at queueOptions as well, but still I was not able to dequeue the message.

A: Finally found answer on some Oracle FAQ: https://docs.oracle.com/cd/B10501_01/appdev.920/a96587/qfaqs.htm
They advice to remove subscriber in order to remove all messages for that target (consumer, address). Interesting that for AQ you may not have subscribers, but for removing staled messages you can add one, then remove it, like that:
declare
    p$src_queue    varchar2(30) := 'source_queue';
    p$consumer    varchar2(30) := 'CONSUMER';
    p$dst_queue    varchar2(100) := 'dest_queue@dblink';
--
    subscriber SYS.AQ$_AGENT;
begin
    subscriber := SYS.AQ$_AGENT(p$consumer, p$dst_queue, NULL);

    DBMS_AQADM.ADD_SUBSCRIBER(
        queue_name => p$src_queue,
        subscriber => subscriber
    );

    subscriber := SYS.AQ$_AGENT(p$consumer, p$dst_queue, NULL);

    DBMS_AQADM.REMOVE_SUBSCRIBER(
        queue_name => p$src_queue,
        subscriber => subscriber
    );
end;
/


text:
Q: AWS CloudFormation create-stack command results in no stack created I am trying to create a new AWS CodeBuild stack by running:
aws cloudformation create-stack --stack-name codebuild-stack-1229a --disable-rollback --template-body file://codebuild.yml \
  --parameters \
    ParameterKey=DeploymentNamePrefix,ParameterValue=stack-1229a \
    ParameterKey=SourceBranch,ParameterValue=dev \
  --capabilities CAPABILITY_AUTO_EXPAND CAPABILITY_NAMED_IAM

The command returns:
{
    "StackId": "arn:aws-us-gov:cloudformation:us-gov-west-1:xxxxxxxxxxxx:stack/codebuild-stack-1229b/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
}

I added --debug switch to the command resulting this output (last several lines):
2021-12-29 12:08:23,512 - MainThread - botocore.endpoint - DEBUG - Sending http request: <AWSPreparedRequest stream_output=False, method=POST, url=https://cloudformation.us-gov-west-1.amazonaws.com/, headers={'Content-Type': b'application/x-www-form-urlencoded; charset=utf-8', 'User-Agent': b'aws-cli/2.4.7 Python/3.8.8 Darwin/20.6.0 exe/x86_64 prompt/off command/cloudformation.create-stack', 'X-Amz-Date': b'20211229T180823Z', 'Authorization': b'AWS4-HMAC-SHA256 Credential=xxxxxxxxxxxx/20211229/us-gov-west-1/cloudformation/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=xxxxxxxxxxxx', 'Content-Length': '3850'}>
2021-12-29 12:08:23,512 - MainThread - botocore.httpsession - DEBUG - Certificate path: /usr/local/aws-cli/awscli/botocore/cacert.pem
2021-12-29 12:08:23,513 - MainThread - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): cloudformation.us-gov-west-1.amazonaws.com:443
2021-12-29 12:08:24,200 - MainThread - urllib3.connectionpool - DEBUG - https://cloudformation.us-gov-west-1.amazonaws.com:443 "POST / HTTP/1.1" 200 402
2021-12-29 12:08:24,200 - MainThread - botocore.parsers - DEBUG - Response headers: {'x-amzn-RequestId': 'xxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx', 'Content-Type': 'text/xml', 'Content-Length': '402', 'Date': 'Wed, 29 Dec 2021 18:08:23 GMT'}
2021-12-29 12:08:24,200 - MainThread - botocore.parsers - DEBUG - Response body:
b'<CreateStackResponse xmlns="http://cloudformation.amazonaws.com/doc/2010-05-15/">\n  <CreateStackResult>\n    <StackId>arn:aws-us-gov:cloudformation:us-gov-west-1:xxxxxxxxxxxx:stack/codebuild-stack-1229b/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</StackId>\n  </CreateStackResult>\n  <ResponseMetadata>\n    <RequestId>xxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx</RequestId>\n  </ResponseMetadata>\n</CreateStackResponse>\n'
2021-12-29 12:08:24,201 - MainThread - botocore.hooks - DEBUG - Event needs-retry.cloudformation.CreateStack: calling handler <bound method RetryHandler.needs_retry of <botocore.retries.standard.RetryHandler object at 0x7fe950eff9d0>>
2021-12-29 12:08:24,201 - MainThread - botocore.retries.standard - DEBUG - Not retrying request.
2021-12-29 12:08:24,201 - MainThread - botocore.hooks - DEBUG - Event after-call.cloudformation.CreateStack: calling handler <bound method RetryQuotaChecker.release_retry_quota of <botocore.retries.standard.RetryQuotaChecker object at 0x7fe950eff610>>
2021-12-29 12:08:24,201 - MainThread - awscli.formatter - DEBUG - RequestId: xxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx
{
   "StackId": "arn:aws-us-gov:cloudformation:us-gov-west-1:xxxxxxxxxxxx:stack/codebuild-stack-1229b/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}

I don't see any errors or warning. The AWS CodeBuild console does not show the build project the command is suppose to create.
Where do I check for any failures? Any suggestion is appreciated.

A: Make sure you're in the correct region - both in CLI and web console.


text:
Q: C - types not matching I'm working on my homework and I don't want someone to do my homework I just want to know what problem with my code is.
Error:

C:\Users\Cojik\Desktop\Codeblocks files\zadaca2_zadatak1\main.c||In function 'main':|
C:\Users\Cojik\Desktop\Codeblocks files\zadaca2_zadatak1\main.c|28|error: invalid operands to binary > (have 'float *' and 'float')|
C:\Users\Cojik\Desktop\Codeblocks files\zadaca2_zadatak1\main.c|29|error: incompatible types when assigning to type 'float' from type 'float *'|
C:\Users\Cojik\Desktop\Codeblocks files\zadaca2_zadatak1\main.c|39|error: invalid operands to binary  (have 'float *' and 'float')|
C:\Users\Cojik\Desktop\Codeblocks files\zadaca2_zadatak1\main.c|63|error: incompatible types when assigning to type 'float' from type 'float *'|
||=== Build failed: 8 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n, i ,j;
    float arr[1000], max1=-999999999999999.0, max4=-999999999999999.0, min2=999999999999999.0, min3=999999999999999.0;
    printf("Enter the number n: ");
    scanf("%d", &n);
    if(n<3||n>30)
        printf("Worng entry!");
    else
    {
        for(i=0;i<n;i++)
        {
            printf("Enter the elements of %d. row: ", i+1);
            for(j=0;j<n;j++)
            {
                scanf("%f", &arr[i]);
            }
        }
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                if(i>j && i<n-1-j)
                {
                    if(arr[i]>max1)
                        max1=arr[i];
                }
                if(j>i && j<n-1-i)
                {
                    if(arr[i]<min2)
                        min2=arr[i];
                }
                if(i>j && j>n-1-i)
                {
                    if(arr[i]<min3)
                        min3=arr[i];
                }
                if(j>i && i>n-1-j)
                {
                    if(arr[i]>max4)
                        max4=arr[i];
                }
            }
        }
        if(max1==max4 && min2==min3)
        {
            printf("Array is simetrical!\n");
            printf("Elements: o1 = %.3f, o2 = %.3f, o3 = %.3f, o4 = %.3f", max1, min2, min3, max4);
        }
        else
        {
            printf("Array is not simetrical!\n");
            printf("Elements: o1 = %.3f, o2 = %.3f, o3 = %.3f, o4 = %.3f", max1, min2, min3, max4);
        }
    }
    return 0;
}

Does my array need to be two-dimensional?  My code is giving the wrong answers if it is two-dimensional and this error appears if it is one-dimensional, which is not intended.

A: Seems your compiler is getting mixed up. Anyway, the initializers of max1 .. max4 are too large for a float. Use a double.
I also note that you do if(max1==max4 && min2==min3), however, it is bad practice to absolutely compare two floating point values. You should compare them equal within epsilon, the machine precision:
#define epsilon 0.0000000001; //(I don't say this value is correct; just an example)
#define ABS(a) (a<0?-a:a)

if(ABS(max1-max4)<epsilon && ABS(min2-min3)<epsilon)