text:
Q: Python programming functions for repeating def main() :
    n = 5
    def repeat(string, n, delim) :

        name = "string" + "delim"
    nametwo = name * n
    print(nametwo)

I need to write a function def repeat(string, n, delim) which returns the string "string"repeated n times, separated by the string deli. exampleL repeat("ho", 3, ", ") "ho, ho, ho"Could someone give me tips how i should go along of writing this?

A: Look at this:
>>> ", ".join("ho" for _ in range(3))
'ho, ho, ho'
>>> def repeat(string, n, delim):
...     return delim.join(string for _ in range(n))
...
>>> repeat("ho", 3, ", ")
'ho, ho, ho'
>>>

Mainly, this takes advantage of the join method of a string and the range built-in.

A: What you're asking for already exists: str.join. join is only doing the hard part; we still need something for the easy part… but that's the easy part.
Also, as others have pointed out, you can use the * operator on strings to get you most of the way there. But, despite having nearly written that yourself, I get the feeling you don't understand why that's most of the way there.
You can even combine the two: delim.join([string] * n). (Here, I'm repeating a list rather than the string itself, because otherwise I'd just get one big string "spamspamspamspamspam" instead of five separate "spam"s to join up.)

But, I'm going to assume this is a homework assignment or a self-teaching attempt, and you want to know how to write it yourself from scratch.
Normally, when you want to repeat something, you want a loop.
If you want to repeat something for each element in the list spam, you write the loop for element in spam:.
But what if you want to repeat it 5 times? There's no "each element in the number 5". You need for find something that has 5 elements. And range(5) is perfect for that. So:
def repeat(string, n, delim):
    for i in range(n):
        # something

Next, you already know how to concatenate strings, with the + operator. So, let's start with an empty string, and concatenate onto the end of it:
def repeat(string, n, delim):
    result = ""
    for i in range(n):
        result = result + string + delim
    return result

But this has a problem:
>>> repeat("spam", 5, ", ")
'spam, spam, spam, spam, spam, '

There's just the right amount of spam, but too many commas.
If you go back to the * solution, you'll see that this is the same thing as (string + delim) * n, we just got there the long way. Either way, you get the same problem.

How do you avoid that?
Here you have to get a bit tricky. You can treat the last value special, or the first one. Or you can look at result so far to see if you're at the start. Or you can just let it add the extra delimiter and then lop it off at the end. I'll show you one of those options, but you should try to write another one yourself. (Looking at result is probably the easiest, and the cleanest, once you figure out how to adjust the algorithm to make it possible.)
def repeat(string, n, delim):
    result = ""
    for i in range(n):
        result = result + string + delim
    return result[:-len(delim)]

The way I lopped off the extra delimiter at the end was by using slicing, with a negative index. You probably haven't learned that yet, which is why you should write a solution for yourself. (Plus, this is probably the hackiest of the solutions.)
Going all the way back to the top, if you play around with join, you'll see that it solves this problem for you. It's obviously not using magic, so you might think about looking at how it's implemented. Unfortunately, it's probably a big mess of C code somewhere in this file, not nice clear Python, so you probably wouldn't learn much.

A: You're so close..
def repeat(string, n, delim):
      name = string + delim
      nametwo = name*n
      print(nametwo)

You don't need the quotes there. With the quotes, the value of name will be "stringdelim", instead of the values of "string" and "delim".

A: >>> def repeat(s, n, d):
...     return d.join([s]*n)
...
>>> repeat("ho", 3, ", ")
'ho, ho, ho'

You can avoid the temporary list (n might be very large) by using itertools.repeat
>>> import itertools as it
>>> def repeat(s, n, d):
...     return d.join(it.repeat(s, n))
...
>>> repeat("ho", 3, ", ")
'ho, ho, ho'

A: def repeat(string, n, delim):
    print((string + delim)*(n-1) + string*(n>0))

>>> repeat('ho', 5, ", ")
ho, ho, ho, ho, ho

A: Here is a recursive version
def repeat(s, n, d):
    if n == 0:
        return ""
    if n == 1:
        return s
    return repeat(s, n/2, d) + d + repeat(s, n - n/2, d)


text:
Q: Scraping flipkart mobile details using Selenium and Python I need to scrape selective details after searching for a phone model on Flipkart. I decided to go through the table and fetch data. Here is the code I am using
# creating a URL variable to store website URL
url_fkrt=('https://flipkart.com')

# Establishing connection with the website
driver.get(url_fkrt)
time.sleep(2)

# Closing the login dialogue box appearing at first visit
try:
    driver.find_element_by_xpath("//button[@class='_2KpZ6l _2doB4z']").click()
except NoSuchElementException:
    pass

# Creating object of the search bar by finding it through Class name
search_bar_fk=driver.find_element_by_class_name('_3704LK')

# Clearing the bar if there is any text in it
search_bar_fk.clear()

# Sending required product to the search bar
search_bar_fk.send_keys('galaxy note 20')

# Creating object of the search button and sending click commamnd
search_btn_fk=driver.find_element_by_class_name('_34RNph')
search_btn_fk.click()
time.sleep(3) # pausing the code for 3 seconds, allowing page to load

# Creating empty lists to store data

phone_name=[]
phone_colour=[]
phone_ram=[]
phone_storage=[]
camera_p=[]
camera_s=[]
display_size=[]
display_resolution=[]
phone_processor=[]
processor_cores=[]
battery_capacity=[]
urls=[]

# Collecting URLs for each product on the page

for links in driver.find_elements_by_xpath("//a[@class='_1fQZEK']"):
    urls.append(links.get_attribute('href'))

# Iterating through the URL list and accessing each link to extract data
for url in urls:
    driver.get(url)
    time.sleep(2)

    # Finding the Read More button and clicking it
    driver.find_element_by_xpath("//button[@class='_2KpZ6l _1FH0tX']").click()
    time.sleep(1)

    # Storing all the table rows
    model=driver.find_elements_by_xpath("//tr[@class='_1s_Smc row']")

    # Iterating through the Table rows to get required data
    for name in model:
        text1=name.find_element_by_xpath("td[1]").text # Storing text for first Table Data for each row to check 'if' condition

        # Extracting Model name
        if text1=='Model Name':
            phone_name.append(name.find_element_by_xpath("td[2]").text)

        # Extracting Phone Color
        if text1=='Color':
            phone_colour.append(name.find_element_by_xpath("td[2]").text)

        # Extracting Display Size
        if text1=='Display Size':
            display_size.append(name.find_element_by_xpath("td[2]").text)

        # Extracting Display Resolution
        if text1=='Resolution':
             display_resolution.append(name.find_element_by_xpath("td[2]").text)

        # Extracting Processor
        if text1=='Processor Type':
            phone_processor.append(name.find_element_by_xpath("td[2]").text)

        # Extracting Cores in Processor
        if text1=='Processor Core':
            processor_cores.append(name.find_element_by_xpath("td[2]").text)

        # Extracting Internal Storage(ROM)
        if text1=='Internal Storage':
            phone_storage.append(name.find_element_by_xpath("td[2]").text)

        # Extracting RAM Memory
        if text1=='RAM':
            phone_ram.append(name.find_element_by_xpath("td[2]").text)

        # Extracting Primary Camera Details
        if text1=='Primary Camera':
            camera_p.append(name.find_element_by_xpath("td[2]").text)

        # Extracting Secondary Camera Details

        if text1=='Secondary Camera':
            camera_s.append(name.find_element_by_xpath("td[2]").text)

        # Extracting Battery Capacity
        if text1=='Battery Capacity':
            battery_capacity.append(name.find_element_by_xpath("td[2]").text)

What I am not able to do is, where the particular details (suppose to say 'processor') is not found for a model then it should append '-' in the list.
Any suggestions?? Or is there any other approach better than this.

A: If I understand you right, you can do something like that for all details:
desc_td = name.find_element_by_xpath("td[2]")
desc_dtl = desc_td.text if desc_td is not None else "-"
phone_processor.append(desc_dtl)
This is to append the value of the product description if it exists, and if not, it will append "-" instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP MVC Claim Based (ADFS) inactivity problems I use a claim based authentication for my ASP MVC web application. It's working well, but after a while (some minutes of inactivity) I received a blank page with nothing. Worst, I can't access to the authenticate page ...
So I think there is a timeout problem ? If I go to the cookies panel with Chrome and delete the cookie named FedAuth, everything back to the normal and instead of the blank page I can access to my app ...
I check the event viewer for ADFS and IIS and there is no error, everything seems ok. Can someone have an idea ?
Thanks!

A: I'm wondering, if ADFS cookies it's related to IIS session timeout ? And also I jusck check the ADFS TokenLifeTime, the value is 480 minutes.

A: After lot of search, it seems that the problem is related to IIS cookie settings, specially the time-out settings (by default 20 minutes).
I change this value and increase it to 60 minutes for my test and in the ADFS side, I put the value none for ExtendedProtectionTokenCheckand. I didn't receive the blank page during the first 60 minutes. But strangely for iOS and MacOS devices, the problem is always there.


text:
Q: Python Extract Not matching indexes in two dataframes I have two data frames master and slave. Both will have the same indexes, sometimes, the master will have more. I want to extract those additional indexes and corresponding data.
My code:
masterdf = pd.DataFrame({'A':np.arange(1.0,9.0)},index=pd.date_range(start='2020-05-04 08:00:00', freq='1h', periods=8))
sldf= pd.DataFrame({'A':np.arange(1.0,5.0)},index=pd.date_range(start='2020-05-04 08:00:00', freq='1h', periods=6))

auxdf = masterdf.reindex(masterdf.index-sldf.index)

Present output:
ValueError: cannot add indices of unequal length

A: Try to use the Index.difference() to get the difference of the 2 indexes for the .reindex():
auxdf = masterdf.reindex(masterdf.index.difference(sldf.index))

Result:
masterdf = pd.DataFrame({'A':np.arange(1.0,9.0)},index=pd.date_range(start='2020-05-04 08:00:00', freq='1h', periods=8))
sldf= pd.DataFrame({'A':np.arange(1.0,7.0)},index=pd.date_range(start='2020-05-04 08:00:00', freq='1h', periods=6))

auxdf = masterdf.reindex(masterdf.index.difference(sldf.index))

print(auxdf)

                       A
2020-05-04 14:00:00  7.0
2020-05-04 15:00:00  8.0


text:
Q: My physical server boot freezes at UEFI: MEM INIT after installing OS Model: LENOVO ThinkSystem SR250
Was able to boot into Provisioning Manager, set up RAID.
After installing Windows Server 2019, it reboots, then stuck at Power On Self Test - UEFI: MEM INIT\
Planned to upgrade UEFI firmware to the latest, but now I can't even boot into System Setup, F1 key has no response...
Any ideas?? THANKS


text:
Q: how to import a .sql file to mysql without selecting the database in wamp i have a .sql file that has many CREATE DATABASES, so i was looking for a command line to import my database that i dont need to select the database, because in my .sql file already has the CREATE DATABASES, i'm working with wampp, someone knows how to do that ?

A: If you are logged into the mysql client, you can use \. file_name
See: http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html
If you only want to create a bunch of databases, without CREATE TABLE or INSERT statements, then you can use USE mysql;. But, if your .sql script contains any CREATE TABLE or INSERT statements, you must use a USE database_name; statement beforehand.


text:
Q: Error during data import to Mariadb 10 I exported my database using PHPMyAdmin running Mariadb 10. Now when I try to import the .sql file in another server running Mariadb 10. The import freezes at some point. After debugging, I realise it freezes at the queries below:
--
-- Indexes for table `user_jobs`
--
ALTER TABLE `user_jobs`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_jobs_queue_reserved_reserved_at_index` (`queue`,`reserved`,`reserved_at`);

--
-- Indexes for table `account_jobs`
--
ALTER TABLE `account_jobs`
  ADD PRIMARY KEY (`id`),
  ADD KEY `jobs_queue_reserved_reserved_at_index` (`queue`,`reserved`,`reserved_at`);

Removing the above from the .sql file, the import runs successfully.
Now when I manually execute the above queries, there run successfully.
Why doesn't this work during the import?
I don't get any special error except that the import just hangs looking at me until I would have to end the process using Ctrl+C
Appreciate help!


text:
Q: Hard Code Logistic Regression Scoring Code I am trying to hard code a logistic regression equation in Python 2.7. I have created a pandas dataframe called df which contains the necessary variables for the equation.
#  score equation
xb = [(-0.2962)
      + (df['wBCC7800'] * 0.4273)
      + (df['wBCX7110'] * 0.4761)
      + (df['wALL7320'] * 0.4061)
      + (df['wBCC5400'] * 0.439)
      + (df['wREH7110'] * 0.322)
      + (df['wBCN0300'] * 0.3241)
      + (df['wBCN8220'] * 0.2148)
      + (df['wBCA7212'] * 0.1905)]

def sigmoid(xb):
    return 1 / (1 + np.exp(-xb))

df['score'] = df.apply(sigmoid, axis=1)

This code results in the following error message:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-30-ca9845eb630d> in <module>()
     13     return 1 / (1 + np.exp(-xb))
     14
---> 15 df['score'] = df.apply(sigmoid, axis=1)

/usr/local/envs/py3env/lib/python3.5/site-packages/pandas/core/frame.py in apply(self, func, axis, broadcast, raw, reduce, result_type, args, **kwds)
   6012                          args=args,
   6013                          kwds=kwds)
-> 6014         return op.get_result()
   6015
   6016     def applymap(self, func):

/usr/local/envs/py3env/lib/python3.5/site-packages/pandas/core/apply.py in get_result(self)
    140             return self.apply_raw()
    141
--> 142         return self.apply_standard()
    143
    144     def apply_empty_result(self):

/usr/local/envs/py3env/lib/python3.5/site-packages/pandas/core/apply.py in apply_standard(self)
    246
    247         # compute the result using the series generator
--> 248         self.apply_series_generator()
    249
    250         # wrap results

/usr/local/envs/py3env/lib/python3.5/site-packages/pandas/core/apply.py in apply_series_generator(self)
    275             try:
    276                 for i, v in enumerate(series_gen):
--> 277                     results[i] = self.f(v)
    278                     keys.append(v.name)
    279             except Exception as e:

<ipython-input-30-ca9845eb630d> in sigmoid(xb)
     11
     12 def sigmoid(xb):
---> 13     return 1 / (1 + np.exp(-xb))
     14
     15 df['score'] = df.apply(sigmoid, axis=1)

/usr/local/envs/py3env/lib/python3.5/site-packages/pandas/core/generic.py in __neg__(self)
   1121         elif (is_numeric_dtype(values) or is_timedelta64_dtype(values)
   1122                 or is_object_dtype(values)):
-> 1123             arr = operator.neg(values)
   1124         else:
   1125             raise TypeError("Unary negative expects numeric dtype, not {}"

TypeError: ("bad operand type for unary -: 'str'", 'occurred at index 0')

I want to create a new variable in the dataframe that contains the logistic regression score.


text:
Q: how to use graph view to represent sqlite data? i have a graph view to implement an analysis graph
All the x-axis and y-axis data is get from the sqlite db data to show the output
x-axis is showing date
y-axis is showing weight
but I have no idea to implement them out, I am stuck,
below is my code but its wrong and I haven't completed yet, can someone help me to solve and build
  DBHelperNote connect = new DBHelperNote(getActivity());
        SQLiteDatabase db = connect.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM weight;",null);

        String[] weight = new String[cursor.getCount()];
        int i = 0;

        while(cursor.moveToNext()){
            d = cursor.getString(cursor.getColumnIndex("weightnum"));
            weight[i] = d;
            i++;
        }

        String[] date = new String[cursor.getCount()];
        int r = 0;
        while(cursor.moveToNext()){
            e = cursor.getString(cursor.getColumnIndex("date"));
            date[r] = e;
            r++;
        }

        GraphView line_graph = (GraphView) contentView.findViewById(R.id.graph);
        LineGraphSeries<DataPoint> line_series =
                new LineGraphSeries<DataPoint>(new DataPoint[] {

>> here "while" getting error

                        while ( a!=weight.length) {
                           new DataPoint(Integer.parseInt(weight[i]), Integer.parseInt(date[i]));
                            i++;
                            }

                }
        );
        line_graph.addSeries(line_series);
        line_series.setDrawDataPoints(true);
        line_series.setDataPointsRadius(10);
        line_series.setOnDataPointTapListener(new OnDataPointTapListener() {
            @Override
            public void onTap(Series series, DataPointInterface dataPoint) {
                Toast.makeText(getActivity(), "Series: On Data Point clicked: " + dataPoint, Toast.LENGTH_SHORT).show();
            }
        });

A: Hmn, it might be an error with the data type in their example they use a double instead of an int.
http://www.android-graphview.org/documentation/category/live-chart
private DataPoint[] generateData() {
        int count = 30;
        DataPoint[] values = new DataPoint[count];
        for (int i=0; i<count; i++) {
            double x = i;
            double f = mRand.nextDouble()*0.15+0.3;
            double y = Math.sin(i*f+2) + mRand.nextDouble()*0.3;
            DataPoint v = new DataPoint(x, y);
            values[i] = v;
        }
        return values;


text:
Q: Android : is it possible to listout all the install application name and icon in list View? I want to make an application in which I can see all the installed applications on my device.
Is it possible to display all the applications in a List View?
If yes then how?

A: Absolutely! In fact, that's how your home launcher works!

*

*First you need access to the ApplicationInfo, but this information is all distributed via the system's PackageManager.
PackageManager _pm = getPackageManager();
OR
PackageManager _pm = context.getPackageManger();

*Now, you just ask it for what you want.
List _list = _pm.getInstalledApplications(flags);
// Flags can be GET_UNINSTALLED_PACKAGES, GET_SHARED_LIBRARIES, GET_METADATA, or any combination. If you want none of these, just set it to 0.

*Now you just take that list and dump it into an Adapter. (Of course, you have to make one for yourself :).
Hope this helps,
FuzzicalLogic


text:
Q: Cannot find usb device iot core Trying to connect to my APC UPS via USB and send it raw data.
Package.appxmanifest
    <DeviceCapability Name="usb">
  <Device Id="vidpid:051D 0002">
    <Function Type="name:vendorSpecific"/>
  </Device>
</DeviceCapability>

StartupTask.vb
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Net.Http
Imports Windows.ApplicationModel.Background

' The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409

Public NotInheritable Class StartupTask
    Implements IBackgroundTask

        Public Async Sub MainPage_Load(sender As Object, e As RoutedEventArgs) Handles MyBase.Loaded
    Dim VID As UInt32 = &H51D
    Dim PID As UInt32 = &H2

    Dim filter As String = Windows.Devices.Usb.UsbDevice.GetDeviceSelector(VID, PID)
    Dim dev As Windows.Devices.Enumeration.DeviceInformationCollection = Await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(filter, Nothing)
    If dev.Count > 0 Then
        Dim device As Windows.Devices.Usb.UsbDevice = Await Windows.Devices.Usb.UsbDevice.FromIdAsync(dev(0).Id)
    End If
End Sub

Issue is device comes up as nothing. dev.Count is 1.


text:
Q: error:Manager isn't available; 'auth.User' has been swapped for 'Log.CUstomUser' in Django When a user wants to register, my website show this error:

Manager isn't available; 'auth.User' has been swapped for
  'Log.CUstomUser'

I use import AbstractUser in my model
I work with Django freamwork python
Model:
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser ,
from django.db import models

# Create your models here.

class CustomUser(AbstractUser):
    country = models.CharField(max_length=200)
    number = models.IntegerField(default=1)
    age = models.IntegerField(default=1)

View:
from __future__ import unicode_literals
from .forms import Register
from django.shortcuts import render , render_to_response
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

# Create your views here.
@csrf_exempt
def Home(request):
    if request.method == "POST":
        form =  Register(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse("Greate")
    else:
        form = Register()
        return render_to_response('home.html' , {'form':form})

Forms:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User

class Register(UserCreationForm):
    email = forms.EmailField(required = True)
    number = forms.IntegerField()
    age = forms.IntegerField()

    class meta:
        model = User
        field = (

            'number',
            'age',
            'username',
            'firstname',
            'lastname',
            'email',
            'password1',
            'password2'

        )

Please, help me to fix my error.

A: Did you change this var in settings?
 AUTH_USER_MODEL = 'yourapp.CustomUser'
More details you can get there

A: Im new in django but i have an idea for ur error maybe help.
try to replace model = CustomUser instead model=User in Form.py as below:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User

class Register(UserCreationForm):
        #blah blah

    class meta:
        model = CustomUser    #hereeeeee
        field = (
          #your field
        )


text:
Q: Custom Products Export Code working in Localhost but not working in Live site I have code for export like sku, category id and category path name of sku,
code :
<?php
error_reporting(E_ALL | E_STRICT);
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
// Mage::setIsDeveloperMode(true);
//ini_set('display_errors', 1);
Mage::app();
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_ids');
//$products->addAttributeToFilter('status', 1);//optional for only enabled products
//$products->addAttributeToFilter('visibility', 4);//optional for products only visible in catalog and search
$fp = fopen('var/export/exports.csv', 'w');
$csvHeader = array("sku", "category_ids","category_name");
fputcsv($fp, $csvHeader,",");
$cat_name = array();
$cat_array = array();
$categoryFullPaths = getCategoryData();
foreach ($products as $product) {
    $sku = $product->getSku();
    $categoryIds = implode('/', $product->getCategoryIds()); //change the category separator
    $_cate_name = join(',', get_values_for_keys($categoryFullPaths, $product->getCategoryIds()));
    fputcsv($fp, array($sku, $categoryIds,$_cate_name), ",");
}
fclose($fp);

function get_values_for_keys($mapping, $keys)
{
    $output_arr = array();
    foreach ($keys as $key) {
        $output_arr[] = $mapping[$key];
    }
    return $output_arr;
}

function getCategoryData()
{
    $category = Mage::getModel('catalog/category');
    $tree = $category->getTreeModel();
    $tree->load();

    $ids = $tree->getCollection()->getAllIds();
    $categories = array();
    $rootCategoryId = Mage::app()->getStore('english')->getRootCategoryId();
    if ($ids) {
        foreach ($ids as $id) {
            $category->load($id);
            $categories[$id]['name'] = $category->getName();
            $categories[$id]['path'] = $category->getPath();
        }
        foreach ($ids as $id) {
            $path = explode('/', $categories[$id]['path']);
            $string = '';
            foreach ($path as $pathId) {
                if ($pathId == 1 || $rootCategoryId == $pathId) continue;  // Uncomment commented code if you want to remove Default Category name.
                $string.= $categories[$pathId]['name'] . '/';
            }

            $categoryFullPaths[$id] = rtrim($string,"/");
        }
    }
    return $categoryFullPaths;
}

Its perfectly working in localhost, when I try to live site its not working

A: You need to do your code like this,
<?php
try
{
    error_reporting(E_ALL | E_STRICT);
    define('MAGENTO_ROOT', getcwd());
    $mageFilename = MAGENTO_ROOT . '/app/Mage.php';
    require_once $mageFilename;
    Mage::app();

    function getCategoryData()
    {
        $category = Mage::getModel('catalog/category');
        $tree = $category->getTreeModel();
        $tree->load();

        $ids = $tree->getCollection()->getAllIds();
        $categories = array();
        $rootCategoryId = Mage::app()->getStore('english')->getRootCategoryId();
        if ($ids)
        {
            foreach ($ids as $id)
            {
              $category->load($id);
              $categories[$id]['name'] = $category->getName();
              $categories[$id]['path'] = $category->getPath();
            }
            foreach ($ids as $id)
            {
                $path = explode('/', $categories[$id]['path']);
                $string = '';
                foreach ($path as $pathId)
                {
                      if($pathId == 1 || $rootCategoryId == $pathId ) continue;
                      $string.= $categories[$pathId]['name'] . '/';
                }
                $categoryFullPaths[$id] = rtrim($string,"/");
            }
        }
        return $categoryFullPaths;
    }

    function get_values_for_keys($mapping, $keys)
    {
        $output_arr = array();
        foreach($keys as $key)
        {
            $output_arr[] = $mapping[$key];
        }
        return $output_arr;
    }

    $products = Mage::getModel("catalog/product")->getCollection();
    $products->addAttributeToSelect('category_ids');

    $fp = fopen('var/export/exports.csv', 'w');
    $csvHeader = array("sku", "category_ids","category_name");
    fputcsv( $fp, $csvHeader,",");
    $cat_name = array();
    $cat_array = array();
    $categoryFullPaths = getCategoryData();
    foreach ($products as $product)
    {
        $sku = $product->getSku();
        $categoryIds = implode('/', $product->getCategoryIds());//change the category separator
        $_cate_name = join(',', get_values_for_keys($categoryFullPaths, $product->getCategoryIds()));
        fputcsv($fp, array($sku, $categoryIds,$_cate_name), ",");
    }
    fclose($fp);
}
catch (Exception $e)
{
    echo $e->getMessage();
}
?>


text:
Q: Get a Position from Gyroscope and Accelerometer I implemented a mathematical method to calculate the position using an IMU that gave me accelerometer, gyroscope and pitch yaw and roll data. The problem was that the IMU was not robust enough to my project so I bought a more precise IMU.
The problem is that it does not give me pitch yaw and roll data, it only gives acceleration and gyroscope data. I know that it easy to calculate pitch and roll, but I guess that I need a magnetometer to calculate yaws value.
I need to calculate the position using this IMU so I do not know what it would be the best method.
1) Get yaw data using mathematical method (I do not know if it is possible).
2) Integrate magnetometer to get yaw data, so I will have enough information to get the position.
3) Use other mathematical method to calculate the position that only needs accelerations and gyros.
Any information you can provide me would be greatly appreciated.

A: if you get acceleration, you could integrate it to get velocity and integrate the velocity to get position. but you need both acceleration and time.


text:
Q: Testing the object type of a parameter passed into a actionscript function? How do you check if an Object passed into a function is the one you are expecting?
public function writeRecord(grid:IExtendedDataGrid, record:Object):String
{

    ExternalInferface.call("alert","record " + record);

    if (record.contains("HotListItem")
    {
        //# I have found my object

    }
    else
    {
        //# Wrong type of object

    }

}

When I display my object to the ExternalInterface alert call it displays the following...

record [object HotListItem]

I would like to be able to test for this type of Object beforehand.

A: Using the is operator has resolved my question.
I tried the instanceof operator but this was flagged as deprecated.
Thanks to Organis
if (record is HotListItem)


text:
Q: Order parent model using children in rails I have model product and vote, I need to order products by votes count DESC.
product has_many :votes, vote belongs_to :product
index_controller.rb
def index
  @products = Product.all
end

A: @products = Product.order("count(votes) DESC")

If you have not votes column then use:
@products = Product.all.sort { |a, b| b.votes.count <=> a.votes.count   }


text:
Q: Copying database from one computer to another Me and my friend both have sql server 2012. I have a database where I would like to copy over most of the tables into a database on my friends laptop. I am not sure not sure how to go about doing this?
I know in sql server that I can copy over data from one table in say database A to database B using the line below.
 select * into database_a.dbo.MyTable from database_a.dbo.MyTable

What is the best way to connect the two laptops?

A: You could take a full backup and give it to him to restore. Or you could give him a copy of the *.mdf file and let him attach it to his DB.

A: There are two main options, one is to back up the database and send it to your friend. To do this right click on the database, Tasks and Backup. The problem with this approach is that if you're running even slightly different versions you may have issues.
The alternative is to script the database. To do this right on the database, click Tasks and Generate Scripts. Make sure you choose to script data and schema from the advanced options.
The latter is my preferred approach (as it's much more editable and human readable).


text:
Q: Inequality with concave functions in expected values I'm working on an engineering problem and I manage to reduce it to the following claim, but I'm not sure if it is true. It will be great if someone can give me some ideas!
Let $u(x)$ is an increasing and concave function such that $u(0)=0$.
Let $X_1,..X_n$ be n random variables independently and identically distributed with support $S\subseteq[0,\infty)$, and define $Y_j=r_j X_j$ where $0<r_1\leq r_2 \leq...\leq r_n$ are given.
Problem:
Is it always possible to find a probability vector $p\in\mathbb{R}^n$ (i.e $p\geq0$ and $\sum_{i=1}^{n} p_i = 1$), such that $\forall i$:
$\mathbb{E}[u(p_i\sum_{j=1}^{n} Y_j)-u(Y_i)]>0$
Idea: Maybe this helps: I can prove that the claim is true IF the next claim is also true (but clearly I don't know if it is):
$\forall p \exists i$:
$\mathbb{E}[u(p_i\sum_{j=1}^{n} Y_j)-u(Y_i)]>0$
Notes: I believe it is possible, and I have tried using Jensen, Karamata, subadditivity, and Sperner's lemma, but none of these work. Any idea will be super welcome.
Thanks!


text:
Q: Aptana Studio and tabbing through html nodes I love that I can tab through {}, [], (), etc. in Aptana but when I'm editing HTML and the existing node I'm currently editing is highlighted with the same light-grey border I inevitably try to step through it when I'm done by hitting tab and re-discover it doesn't work.

Am I missing a really obvious keyboard shortcut?

A: Shift+Enter will jump to the next line (while also adding a new line after the current one), but I don't think there is a shortcut to cycle past it normally.


text:
Q: Extracting(Clipping) in Google Earth Engine I am working with Google earth Engine and I am trying to extract/Filter (clip)  pixels in a band using another image (band). I calculated NDVI and created a threshold value that rendered an image with NDVI > 0.3 but I wanted to extract the corresponding pixels in the visible an NIR bands.
Here is snippet code.
var s2 = ee.ImageCollection('COPERNICUS/S2');
var s2_filtered = s2.filterDate('2017-01-01', '2017-12-31')
                  .filterBounds(geometry) //custom Geometry

var calcNDVI = function(x){
  var ndvi4 = x.normalizedDifference(["B5", "B4"]).rename("ndvi")
  return x.addBands(ndvi)
}

var ndviCollection = s2_filtered.map(calcNDVI)
var maxNDVI = mosaic.select("ndvi");
var threshold = maxNDVI.gt(0.3)

I am at the point where I wanted to clip the corresponding pixels in "B", "G", "R" and "NIR" bands using the threshold variable(image). Obviously, I'm stuck here. Please let me know if there is with a way to filter/clip pixels of one band using another band with in GEE. The task is similar to using Clipper in QGIS which is the options I am left with if this doesn't work.
Thanks for your help!

A: The variable threshold is a mask, so you have to mask out pixels in the mosaic using the threshold mask, right? If that is the case, simply update the mask of the image:
var masked = maxNDVI.updateMask(threshold)


text:
Q: Can we use same Configmap for different volume mounts? Two pods are running and have different volume  mounts, but there is a need of using the same configmap in the 2 running pods.

A: Sure you can do that. You can mount same ConfigMap into different volume. You can take a look into configure-pod-configmap.
Say, your ConfigMap is like following:
apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm

And two pods:
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod-01
spec:
  containers:
    - name: test-container
      image: busybox
      command: [ "/bin/sh", "-c", "ls /etc/config/" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: special-config
  restartPolicy: Never
---
apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod-02
spec:
  containers:
    - name: test-container
      image: busybox
      command: [ "/bin/sh", "-c", "ls /etc/config/" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: special-config
  restartPolicy: Never

Now see the logs after creating the above ConfigMap and two Pods:
# for 1st Pod
$ kubectl logs -f dapi-test-pod-01
SPECIAL_LEVEL
SPECIAL_TYPE

# for 2nd Pod
$ kubectl logs -f dapi-test-pod-02
SPECIAL_LEVEL
SPECIAL_TYPE


text:
Q: unable to locate pip packages using asdf in VSC I have just installed a fresh install of BigSur and Python (using asdf) when installing pip packages they seem to end up in:
./.asdf/installs/python/3.9.2/lib/python3.9/site-packages
when typing which flake8 for example I get flake8 not found but when I go to install it again pip install flake8 I get the following:
> which flake8
flake8 not found

~
> pip install flake8
Requirement already satisfied: flake8 in ./.asdf/installs/python/3.9.2/lib/python3.9/site-packages (3.8.4)
Requirement already satisfied: pycodestyle<2.7.0,>=2.6.0a1 in ./.asdf/installs/python/3.9.2/lib/python3.9/site-packages (from flake8) (2.6.0)
Requirement already satisfied: mccabe<0.7.0,>=0.6.0 in ./.asdf/installs/python/3.9.2/lib/python3.9/site-packages (from flake8) (0.6.1)
Requirement already satisfied: pyflakes<2.3.0,>=2.2.0 in ./.asdf/installs/python/3.9.2/lib/python3.9/site-packages (from flake8) (2.2.0)

I have just tried to use requests which I installed like pip install requests and I also got not found when using which but I manage to use the package in VSC ok.
I am using flake8 and Black and I need to give VSC their paths. I have used
./.asdf/installs/python/3.9.2/lib/python3.9/site-packages/<package name>
but VSC doesn't seem to pip it up. I am using the latest verisons.
> python -V
Python 3.9.2

~
> pip -V
pip 21.0.1 from /Users/paul/.asdf/installs/python/3.9.2/lib/python3.9/site-packages/pip (python 3.9)

this might help too:
~
> which python
/Users/paul/.asdf/shims/python

~
> which pip
/Users/paul/.asdf/shims/pip

Any idea how I can get which to display the correct paths so I can get my listing and formatting working ok?

A: This fixed it... https://til.hashrocket.com/posts/ques11vrjs-get-pip-installed-executables-into-the-asdf-path
asdf reshim python
I would be curious why I have to do this...if anyone could answer


text:
Q: Does 0 lie on elliptic curve? Does $0$ lie on an elliptic curve, where $0$ is the identity (e.g. $p + 0 = p$)?

A: Every elliptic curve $E$ over a field $k$ is isomorphic to the locus in $\mathbf{P}_k^2$ cut out by a nonsingular Weierstrass equation in such a way that the given rational point on $E$ is mapped the point at infinity. So I guess the answer to your question is yes.


text:
Q: Is setting substruct values to values returned by pure virtual functions safe in an object constructor? Consider (note some code removed from object, i.e. constructors/destructors and some variables):
struct object {
    virtual bool object_is_solid() = 0;
    virtual bool object_is_visible() = 0;
    virtual bool object_is_persistent() = 0;
    virtual real_t object_depth() = 0;
    virtual real_t object_sprite_index() = 0;
    virtual real_t object_mask_index() = 0;

    struct object_properties {
      bool solid;
      bool visible;
      bool persistent;
      real_t depth;
      real_t sprite_index;
      real_t mask_index;
      real_t image_alpha;
      real_t image_angle;
      real_t image_blend;
      real_t image_index;
      real_t image_speed;
      real_t image_xscale;
      real_t image_yscale;
      real_t hfriction;
      real_t vfriction;
      real_t hgravity;
      real_t vgravity;
      real_t hspeed;
      real_t vspeed;
    } properties;

    void initialize_properties(object::object_properties& prop);
}

and
  object::object(unsigned long id, real_t x, real_t y)
    : id(id), xstart(x), ystart(y), x(x), y(y), xprevious(x), yprevious(y), properties{} {
    this->initialize_properties(this->properties);
  }

  void object::initialize_properties(object::object_properties& prop) {
    prop.solid = this->object_is_solid();
    prop.visible = this->object_is_visible();
    prop.persistent = this->object_is_persistent();
    prop.depth = this->object_depth();
    prop.sprite_index = this->object_sprite_index();
    prop.mask_index = this->object_mask_index();
    prop.image_alpha = 1;
    prop.image_speed = 1;
    prop.image_xscale = 1;
    prop.image_yscale = 1;
  }

Notice the usage of initialize_properties.

*

*Is this even safe? If I inline initialize_properties manually, clang refuses to compile it because it's calling pure virtual functions in the constructor.

*Is there a better way for me to initialise properties than what I am doing right now?

A: Short answer: don't do it.
Explanation:
When object is constructed, the object is of type object, not the derived class yet. Let's call the derived class my_object.
Any virtual function (pure or not) that your in object's constructor will call object's version.
Only in the body of my_object::my_object() the object type is my_object, not before.
The solution is to separate construction from initialization.
From my_object::my_object() call a virtual function Initialize or better, expose it as a public method so the code that created the my_object instance will call it to initialize the object.
Example:
my_object o;
o.Init(params);

A: No, it's not safe.
I'm going to refractor the code so that it's necessary the user call a member function to perform this initialisation. It's not as automatic as I'd like, but it's probably for the best.


text:
Q: Why does Date.now - a given date work? Documentation shows that Date.now() returns the ms since 1970

const daysFromNow = (date) => Math.round((date-Date.now())/(1000*3600*24))

console.log(daysFromNow(new Date('07/04/2020')));

//result is -534

Given the above, why does it work? I've read that .now() gives back the ms since 1970. Does the passed in date hold a value of the ms since 1970 as well?

A:
Does the passed in date hold a value of the ms since 1970 as well?

The Date object represents a specific moment on earth, so yes you can retrieve that the milliseconds since 1970 in milliseconds.
A Date object has a valueOf function that returns the primitive value of the Date:

The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date.

So (new Date()).valueOf() and Date.now() are equivalent:

console.log((new Date()).valueOf())
console.log(Date.now())

And the valueOf is called for conversion in the case of date - Date.now() because date is a Date object and Date.now() returns a number.
Here an example of a custom object with a valueOf function:

let test = {
  valueOf() {
    return 5;
  }
}

console.log(test - 1);

A: That's work because of valueOf property. That property return a number, implemented in all objects in js. You can also owerride it in your objects.
Here an example of using for creating add chain js function.

function add(x) {
  const fn = (y) => add(x + y);
  fn.valueOf = () => x;
  return fn;
}

const addTen = add(5)(5);

console.log(addTen + 1) // 11


text:
Q: Error while creating a react app in my pc there are some folders in my pc where I'm not able to create react apps using npx create-react-app.

this error comes in some directories only.
I've tried installing npx create-react-app globally too. I get this error.

A: This seems to me more like a file permission issue in this folder rather than a problem related to create-react-app. The process fails at creating the app folder (mkdir).
As a first step, I'd check if it's possible to create a folder manually in there by navigating into the folder in Windows Explorer, entering "cmd" in the navigation bar and trying to create a folder at this place (command: "mkdir test").
If this also fails, you should check the folder permissions (right click on the folder, Properties, Security). Your user account should be added to the permissions list with full permissions or at least write/change permissions.


text:
Q: C++: Unexplainable behavior with cout and pointer to char After printing a pointer to an int, I print a pointer to a char:
#include <iostream>

using namespace std;

int main() {

    int i;
    cout << "&i: " << &i << endl;

    char q = 'q';
    cout << "&q: " << &q << endl;

    return 0;

}

I get the following output as expected:
&i: 0xffffcc0c
&q: q

However, if I comment out cout << "&i: " << &i << endl;, and run the program again, I get the following unexplained output:
&q: q����

Does anyone know why this is happening?
If it has to do with operator<< inserting into the stream until it finds a null character, then why do I get the expected output when I include cout << "&i: " << &i << endl;?
NOTE: I am not expecting to get the address of q from cout. I am expecting to get the C string pointed to by &q. What bugs me is how the output just prints the 'q' if I include the line cout << "&i: " << &i << endl; beforehand. However, if I comment that line out, there is garbage data in the output. Why is there not garbage data in my output when I include the line cout << "&i: " << &i << endl;?

A: The bit &q thinks it is a string.
Therefore will print up to the null character. hence the extra output


text:
Q: How to make timer before multiplayer game start in unity 5.? Here I am trying to create a multiplayer game. I want to put timer before game start so, I do research, but can't get any solution for this. I am currently using
"Coroutine" for this. but not working.it show different time for all players.
private int j = 10;

void Start()
{
    if (isLocalPlayer)
    StartCoroutine (GameStartTimer ());
}

IEnumerator GameStartTimer()
{
    while (j > 0) {
        j = j - 1;
        Debug.Log ("Value of j is : " + j);
        startTimertext.text = j.ToString ();
        yield return new WaitForSeconds (1);
    }
    //ObjectParentingSystem ();
    GetPlayerAnimandRGB ();
    StartCoroutine (StartPlayerTimer ());
    //yield return new WaitForSeconds (10);
    gameStartTextPanel.SetActive (false);
}

I also try below code but, can't get succes.
void Start()
{
    if (isServer){
        StartCoroutine (GameStartTimer ());
    }
    else{
        GetPlayerAnimandRGB ();
        StartCoroutine (StartPlayerTimer ());
        //yield return new WaitForSeconds (10);
        gameStartTextPanel.SetActive (false);
    }
}

If any one have code for this or tutorials then pls share link.

A: If I understand this right, you've a wait timer that keeps ticking for 10 seconds. Once this is zero, the start game timer begins and only those connected can play the game.
To keep all players and timers in sync you will have to either designate one client as the server responsible for keeping all other clients in sync or have a server broadcast the time to all players who connect to the room. Without this, you will not be able to keep the time in sync as players don't join the room at the same time.


text:
Q: MySQL Syntax Issue with CONCAT AND LIKE I have a stored procedure to capture an id. It concat's the last name with first name as
"William, John" and compares with the _fullname passed which when i var_dump gives
String(13) Willam, John
Hence it should give an id.
IF NOT ISNULL(_fullname) THEN
            SET _fullname       = TRIM(_fullname);
            SET clause = CONCAT( clause , ' AND CONCAT(c.lname, ', ', c.fname) LIKE CONCAT('%',_fullname,'%')');

When i try the same query in MySQL it works perfectly fine. I'm sure that the problem is syntax in stored procedure. Can you check.


text:
Q: how to bind a specific ip to a mongodb service? I want to send a request to mongodb in a remote server machine.  The following line is in the configuration, and I am not allowed to remove it:
bindip:127.0.0.1

I want to bind the IP 45.56.65.100 to my mongodb service on Windows.
Can I include 45.56.65.100 in ip to solve the problem?

A: You can bind one IP as shown above "bindip:127.0.0.1"
All IPs for the machine using: "bindip:0.0.0.0"
Or multiple IPs as notated here:

https://stackoverflow.com/a/36450320/2585788

bindIp: 172.31.60.184,127.0.0.1
  Remember to not put a space after the comma.
  answered Apr 6 at 11:50 Puneet Goyal

Please make sure to also up-vote the original related answer.


text:
Q: Data passed as props is not updating in Vue 2 I can't understand why data passed as props is not updating when data changes. I tried different ways, but for some reason, the frontend knows nothing about data manipulation. Here is my code base:
For Loop
<SingleElement v-for="addon of addons" :key="addon.id"
  :id="addon.id"
  :title="addon.name"
  :description="addon.description"
  :active="addon.active" // This is the part I need to update
></SingleElement>

The SingleElement Template
<template>
  <div class="column is-4">
    <b-field>
      <b-switch v-model="isActive"></b-switch>
    </b-field>
  </div>
</template>

<script>
import { store, methods } from '../../../store';

export default {
  name: "single-element",
  props: {
    id: Number,
    title: String,
    description: String,
    active: Boolean,
    docURL: String,
    category: String
  },
  data() {
    return {
      "isActive" : this.active
    }
  },
}
</script>

The Store
import axios from "axios";

export const store = Vue.observable({
  "addons": [],
  "activatedAddons": [],
  "settings": {}
});

export const methods = {
  activateAllAddons() {
    store.activatedAddons = [];
    for (let addon of store.addons) {
      store.activatedAddons.push(addon.id);
      addon.active = true;
    }
  },
  deactivateAllAddons() {
    store.activatedAddons = [];
    for (let addon of store.addons) {
      addon.active = false;
    }
  },
}

The process in short: On click, I call the store method activateAllAddons or deactivateAllAddons. These methods are changing the store.activatedAddons and store.addons data. For example I change the active boolean. But my switch do not react to this changes. Why?
*What I tried
I tried to change the data in different ways.
Way 1
-> Changing the addon boolean in the store
:active="addon.active"
Way 2
-> Creating an additional method to check the status:
:active="isActive(addon)"

and:
isActive(addon) {
  return store.activatedAddons.includes(addon.id);
}

But no way. The frontend seems to know nothing about the changes. When I log the variables in the console, the changes definitely are there. What's the problem here?


text:
Q: cURL retrieve only header without doing HEAD So I am trying to retrieve only headers using cURL with the following:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);

The problem is that while trying to get headers of large file the script uses all the memory. I would like to avoid getting also the body and I have tried to use:
curl_setopt($ch, CURLOPT_NOBODY, true);

The problem is that this issues a HEAD request instead of GET. And some website retrun an error when you request with HEAD.
Is there any way with curl to retrieve only header without doing HEAD request?

A: First, don't use CURLOPT_RETURNTRANSFER as that's the option that makes it keep the entire response in memory.
Then, two options:
A) use a write callback and make that abort the transfer as soon as the first byte of the body is returned. There's a write callback example in the PHP.net docs.
B) use CURLOPT_RANGE and ask for only the first byte to be retrieved, 0-0. This avoids the write callback but has the downside that not all HTTP servers and URLs will acknowledge it.

A: If you dont have to use cURL, you could use get_headers(). By default get_headers uses a GET request to fetch the headers. And you could also modify that request by using stream_context_set_default()
$headers = get_headers('http://example.com');

More Info: PHP: get_headers


text:
Q: Find max value in a column knowing only a part of the value I'm stuck with finding the max value in a column based on a criteria that I know only a part of it.
Let me explain better, here is my table

What I would like to do is:
1) Find the max number in Column A based on my 1st criteria that is "1".
2) If I have the criteria "1" I would like to find the max number that begins with "1", so in our example the max number would be "10010".
Some tips of how I would obtain this? If you prefer VBA is a valid option also.
Thank you

A: One option, something like the following:
=MAX(IF(LEFT(A2:A8,1)="1",A2:A8))

Array formula, so depending on your version of Excel you may need to confirm with  Ctrl+Shift+Enter.


text:
Q: How to get column value from sample data frame in pandas? I want to do following process:

*

*Get sample random row form data frame.
df = df.sample()

*Then I want to get value from column 'amount' I do following, but it is not working.
amount = df['auth_amount'].iloc[0]
Anyone knows how do do it. My code works only for first row.


text:
Q: Binding Issue constructor viewmodel I relatively new to mvvm, however I have a question about binding from a viewmodel.
I have a viewmodel where in its constructor I want to populate a observablecollection.
My constructor looks like this:
public StudySelectionViewModel() : base() {
        _studyRepository = StudyRepository.Instance;

        InitializeViewModelData();
    }

The InitializeViewModelData() looks like this:
        private void InitializeViewModelData() {
        _studyRepository.RetrieveModalityTypes();
        RaisePropertyChanged("ModalityTypes");
    }

My property ModalityTypes looks like this:
public ObservableCollection<ModalityType> ModalityTypes {
        get {
            return _studyRepository.ModalityTypes;
        }
    }

Probably needless to say that my repository makes a call to a database and retrieves the data.
When debugging it looks like that the RaisePropertyChanged is executed earlier than my _studyRepository.RetrieveModalityTypes method is executed and hence it binds to an empty property.
Am I missing something here? Is my design bad? Any ideas?
Thanks in advance,

A: The binding will inspect the property when the form initialises. It will also inspect the property when the PropertyChanged notification is raised - so you may get two calls to the getter of the property
I'm assuming that your call to get data is a web service call or something? Silverlight is async, so you need to consider that web service calls may return well after your form is initialised

A: There are two things to consider here.

*

*You have an ObservableCollection - it's observable, so if you initialise the collection when you initialise the view model, the add to the collection rather than replacing it with a new collection when your data service returns the view will update fine.

*If you really must replace the collection with a new collection in the data service data ready callback, then ensure you write the collection setter thus:
public ObservableCollection<ModalityType> ModalityTypes {
get {
    return _studyRepository.ModalityTypes;
}
set
   {
      this.__studyRepository.ModalityTypes = value;
      RaisePropertyChanged("ModalityTypes");
   {

}


text:
Q: Is it possible to make these functions shorter I create there three functions. I'm thinking of making it shorter or combine into one function. Is it possible?
Here is my code!
$(function(){
   $(".js-disable-form").on("submit", function() {
     $('#loading-modal').modal('show');
     $(this).find("input[type=submit]").prop('disabled', true);
   })
});

$(function(){
  $(".js-disable-form-approval").on("submit", function() {
    var res = confirm("入力内容で承認します。よろしいですか?");
    if (res == true) {
      $('#loading-modal').modal('show');
      $(this).find("input[type=submit]").prop('disabled', true);
    } else {
     return false;
      }
    })
});

$(function(){
  $(".js-disable-form-individual").on("submit", function() {
    $(this).find("input[type=submit]").prop('disabled', true);
  })
  $('.js-disable-btn').on("click", function() {
    $('#loading-modal').modal('show');
  })
});

A: This should do it:
function showModal() { $('#loading-modal').modal('show'); }

function disableSubmit() { $(".js-disable-form input[type=submit]").prop('disabled', true); }

$(function() {
  $(".js-disable-form").on("submit", function() {
    showModal();
    disableSubmit();
  });

  $(".js-disable-form-approval").on("submit", function() {
    if (confirm("入力内容で承認します。よろしいですか?")) {
      showModal();
      disableSubmit();
    } else return false;
  });

  $(".js-disable-form-individual").on("submit", disableSubmit);
  $('.js-disable-btn').on("click", showModal);
});

This isn't much shorter than the original code but should show how to avoid duplicate code in general.

A: You could at least put all event handlers into one function:
$(function(){
    $(".js-disable-form").on("submit", function() {
        $('#loading-modal').modal('show');
        $(this).find("input[type=submit]").prop('disabled', true);
    })

    $(".js-disable-form-approval").on("submit", function() {
        var res = confirm("入力内容で承認します。よろしいですか?");
        if (res == true) {
            $('#loading-modal').modal('show');
            $(this).find("input[type=submit]").prop('disabled', true);
        } else {
            return false;
        }
    })

    $(".js-disable-form-individual").on("submit", function() {
        $(this).find("input[type=submit]").prop('disabled', true);
    })

    $('.js-disable-btn').on("click", function() {
        $('#loading-modal').modal('show');
    })
});

A: $('[class^=".js-disable-"').on("submit", function(){
    if ($(this).className.indexOf("individual") >= 0 || $(this).className.indexOf("form") >=0){
        $(this).find("input[type=submit]").prop('disabled', true);
        if ($(this).className.indexOf("individual") >= 0 ){
            $('.js-disable-btn').on("click", function() {
                $('#loading-modal').modal('show');
            })
        }
        else{
            $('#loading-modal').modal('show');
        }
    }
    else {
        var res = confirm("入力内容で承認します。よろしいですか?");
        if (res == true) {
            $('#loading-modal').modal('show');
            $(this).find("input[type=submit]").prop('disabled', true);
        }
        else {
            return false;
        }
    }
});

Didn't test since there's no html attached. Basicly it matches the classes that starts with .js-disable- and attaches a submit event. Then it's just reranging of your functions.


text:
Q: How to do internal redirecting in reactjs? I'm kinda new to react and was wondering how to internally redirect your pages in reactjs. I have two pages called register and register2. In register page, I just check if the email exists in the database or not and if it doesn't exist then it redirects to register2 page for creating the full account with username and password. However, in the address bar, it kinda looks ugly to show something like register2. So I was wondering if there is any way through which I can internally redirect without changing the address in the address bar to register2 such that it stays as register throughout the whole account creation process.
I created a codesandbox to show the issue
register.js
import React, { useState } from "react";
import { Formik } from "formik";
import TextField from "@material-ui/core/TextField";

import * as Yup from "yup";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
import Link from "@material-ui/core/Link";
import Grid from "@material-ui/core/Grid";
import Box from "@material-ui/core/Box";
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";

function Copyright() {
  return (
    <Typography variant="body2" color="textSecondary" align="center">
      <Link color="inherit" href="sad">
        New1
      </Link>{" "}
      {new Date().getFullYear()}
      {"."}
    </Typography>
  );
}

const useStyles = makeStyles(theme => ({
  paper: {
    marginTop: theme.spacing(8),
    display: "flex",
    flexDirection: "column",
    alignItems: "center"
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main
  },
  form: {
    width: "100%",
    marginTop: theme.spacing(1)
  },
  submit: {
    margin: theme.spacing(3, 0, 2)
  }
}));

const Reg = props => {
  const classes = useStyles();
  const [loginError, setLoginError] = useState("");
  const [changed, setChanged] = useState(false);
  const [newpage, setNew] = useState(false);
  const handleSubmit = async (values, { setSubmitting }) => {
    const { email } = values;

    var body = {
      email: email
    };
    console.log(body);
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify(body)
    };
    const url = "/api/emailcheck";
    try {
      const response = await fetch(url, options);
      const text = await response.text();
      setSubmitting(false);
      setChanged(false);
      setNew(true);
      console.log(text);
      if (newpage) {
        props.history.push({
          pathname: "/register2",
          state: { email }
        });
        // props.history.push(`/register2/${email}`);
      } else if (text === "exists") {
        props.history.push(`/`);
      } else {
        setLoginError("Email is invalid");
      }
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Formik
      initialValues={{ email: "" }}
      onSubmit={handleSubmit}
      //********Using Yup for validation********/

      validationSchema={Yup.object().shape({
        email: Yup.string()
          .email()
          .required("Required")
      })}
    >
      {props => {
        const {
          values,
          touched,
          errors,
          isSubmitting,
          handleChange,
          handleBlur,
          handleSubmit
        } = props;
        return (
          <>
            <Container component="main" maxWidth="xs">
              <CssBaseline />

                <Avatar className={classes.avatar}>
                  <LockOutlinedIcon />
                </Avatar>
                <Typography component="h1" variant="h5">
                  Sign in
                </Typography>
                <form
                  className={classes.form}
                  onSubmit={handleSubmit}
                  noValidate
                >
                  <TextField
                    variant="outlined"
                    margin="normal"
                    required
                    fullWidth
                    id="email"
                    value={values.email}
                    label="Email Address"
                    name="email"
                    autoComplete="email"
                    onChange={e => {
                      setChanged(true);
                      handleChange(e);
                    }}
                    onBlur={handleBlur}
                    className={errors.email && touched.email && "error"}
                  />
                  {errors.email && touched.email && (

                      {errors.email}

                  )}
                  {!changed && loginError && (

                      {loginError}

                  )}

                  <Button
                    type="submit"
                    fullWidth
                    variant="contained"
                    color="primary"
                    className={classes.submit}
                    disabled={isSubmitting}
                  >
                    Next
                  </Button>
                  <Grid container justify="flex-end">
                    <Grid item>
                      <Link href="/" variant="body2">
                        Already have an account? Sign in
                      </Link>
                    </Grid>
                  </Grid>
                </form>

              <Box mt={5}>
                <Copyright />
              </Box>
            </Container>
          </>
        );
      }}
    </Formik>
  );
};

export default Reg;

register2.js
import React, { useState } from "react";
import { Formik } from "formik";
import TextField from "@material-ui/core/TextField";
import { withRouter, useHistory } from "react-router-dom";
import * as Yup from "yup";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
import Link from "@material-ui/core/Link";
import Box from "@material-ui/core/Box";
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";

function Copyright() {
  return (
    <Typography va riant="body2" color="textSecondary" align="center">
      <Link color="inherit" href="sad">
        New
      </Link>{" "}
      {new Date().getFullYear()}
      {"."}
    </Typography>
  );
}

const useStyles = makeStyles(theme => ({
  paper: {
    marginTop: theme.spacing(8),
    display: "flex",
    flexDirection: "column",
    alignItems: "center"
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main
  },
  form: {
    width: "100%",
    marginTop: theme.spacing(1)
  },
  submit: {
    margin: theme.spacing(3, 0, 2)
  }
}));

const Reg2 = props => {
  const classes = useStyles();
  const [loginError, setLoginError] = useState("");
  const history = useHistory();
  const [changed, setChanged] = useState(false);
  const handleSubmit = async (values, { setSubmitting }) => {
    const { username, password } = values;
    var body = {
      username: username,
      password: password,
      email: history.location.state.email
    };
    console.log(body);
    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify(body)
    };
    const url = "/api/register";
    try {
      const response = await fetch(url, options);
      const text = await response.text();
      setSubmitting(false);
      setChanged(false);
      console.log(text);
      if (text === "verifyemail") {
        props.history.push({
          pathname: "/verifyOtp",
          state: { email: body.email }
        });
        // props.history.push(`/verifyOtp/${username}`);
      } else {
        setLoginError("Username or Password is incorrect");
      }
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Formik
      initialValues={{ username: "", password: "", confirmPassword: "" }}
      onSubmit={handleSubmit}
      //********Using Yup for validation********/

      validationSchema={Yup.object().shape({
        username: Yup.string().required("Required"),
        password: Yup.string()
          .required("No password provided.")
          .min(8, "Password is too short - should be 8 chars minimum.")
          .matches(/(?=.*[0-9])/, "Password must contain a number.")
          .matches(
            /(?=.*[●!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/,
            "Password must contain a symbol."
          ),
        confirmPassword: Yup.string()
          .required("Enter to confirm password")
          .oneOf([Yup.ref("password"), null], "Password do not match")
      })}
    >
      {props => {
        const {
          values,
          touched,
          errors,
          isSubmitting,
          handleChange,
          handleBlur,
          handleSubmit
        } = props;
        return (
          <>
            <Container component="main" maxWidth="xs">
              <CssBaseline />

                <Avatar className={classes.avatar}>
                  <LockOutlinedIcon />
                </Avatar>
                <Typography component="h1" variant="h5">
                  Enter Info
                </Typography>
                <form
                  className={classes.form}
                  onSubmit={handleSubmit}
                  noValidate
                >
                  <TextField
                    variant="outlined"
                    margin="normal"
                    required
                    fullWidth
                    id="username"
                    value={values.username}
                    label="username"
                    name="username"
                    autoComplete="username"
                    onChange={e => {
                      setChanged(true);
                      handleChange(e);
                    }}
                    onBlur={handleBlur}
                    className={errors.username && touched.username && "error"}
                  />
                  {errors.username && touched.username && (

                      {errors.username}

                  )}
                  <TextField
                    variant="outlined"
                    margin="normal"
                    required
                    fullWidth
                    name="password"
                    value={values.password}
                    label="Password"
                    type="password"
                    id="password"
                    onBlur={handleBlur}
                    autoComplete="current-password"
                    className={errors.password && touched.password && "error"}
                    onChange={e => {
                      setChanged(true);
                      handleChange(e);
                    }}
                  />
                  {errors.password && touched.password && (

                      {errors.password}

                  )}
                  <TextField
                    variant="outlined"
                    margin="normal"
                    required
                    fullWidth
                    name="confirmPassword"
                    value={values.confirmPassword}
                    type="password"
                    label="Confirm Password"
                    id="confirmPassword"
                    onBlur={handleBlur}
                    autoComplete="confirmPassword"
                    className={
                      errors.confirmPassword &&
                      touched.confirmPassword &&
                      "error"
                    }
                    onChange={e => {
                      setChanged(true);
                      handleChange(e);
                    }}
                  />
                  {errors.confirmPassword && touched.confirmPassword && (

                      {errors.confirmPassword}

                  )}

                  {!changed && loginError && (

                      {loginError}

                  )}
                  <Button
                    type="submit"
                    fullWidth
                    variant="contained"
                    color="primary"
                    className={classes.submit}
                    disabled={isSubmitting}
                  >
                    Next
                  </Button>
                </form>

              <Box mt={8}>
                <Copyright />
              </Box>
            </Container>
          </>
        );
      }}
    </Formik>
  );
};

export default withRouter(Reg2);

A: you could make a parent component for register and register2 and store your logic there in which component to display
function MyComponent() {
  const [email, setEmail] = useState(null)

  useEffect(() => {
    (async () => {
      const response = await yourApiCall()
      setEmail(response)
    })()
  }, [])

  return email ? <Register /> : <Register2 />
}

A: Initially show the register component or code of that sort.
Call an api, if the email exists, store flag value in that and do conditional rendering for another component or code of register2.
Initially, this.state.isEmailExist : false,
After api call change flag value accordingly. If true then render Register2.
const contents = if (!this.state.isEmailExist) {
        return (
            <Register />
        );
    } else {
        return (
            <Register2 />
        )
    }

return(

{contents}

)

A: Maybe you are looking for this
window.open("https://www.youraddress.com","_self");

Make sure to setup the validation.


text:
Q: C++ generating rand numbers In C++ is it possible to use rand to generate a number between 1-52, but stating that it cant be 23? Like for instance creating a blackjack game, you would need to make sure a player cant get the same card after randomly generating the first.

A: int value = rand(1,51);
if (value >= 23) ++value;

where rand(a,b) gives a number in the range [a,b], and could be implemented as std::rand() % (b-a+1) + a, with the caveat that that wouldn't quite be a uniform distribution.

A: Sure.
int i = 23;
while (i == 23)
    i = rand() % 52 + 1;

It's quite common to discard unacceptable values when generating random numbers with a required distribution.
For a blackjack game, though, you need to deal more than one card. It's better to have a full deck and shuffle it (std::random_shuffle), then take cards from one end of whatever container holds the deck.

A: Here's a program that makes a deck from 1 to 52 (inclusive) and prints the deck.
This features STL (and a slightly dated C++ accent)
#include <algorithm>    // std::random_shuffle
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand
#include <iostream>     // std::cout
#include <vector>       // std::vector

int main() {
    std::vector<int> deck;

    // Create deck; deck creation logic goes inside loop
    for (int i = 1; i <= 52; ++i) {
        deck.push_back(i);
    }

    // initialize random number generator and shuffle deck
    std::srand(std::time(0));
    std::random_shuffle(deck.begin(), deck.end());

    // print entire deck
    while (!deck.empty()) {
        int card = deck.back();    // draw card
        std::cout << "Drew " << card << '\n';
        deck.pop_back();           // remove card from deck
    }
}

A: int n=(rand() % 52)+ 1;
while(n==23)
n= n=(rand() % 52) + 1;

http://www.cplusplus.com/reference/cstdlib/rand/

A: Take a look at std::random_shuffle.

A: Another cool way to do this is with an array.
Create a vector:
std::vector<int> possibilities;

Insert possible values to it:
possibilities.push_back(0);
possibilities.push_back(1);
possibilities.push_back(10);

And then pick a random one from it:
int random = possibilites[ rand() % possibilites.size() ];


text:
Q: Find all values of N that satisfy ϕ(N) = x for any given x value How would I determine all values of n in ϕ(n) = x for any value of x where ϕ is Euler's totient function? (and -1 if x is not a totient). Is there a simple formula for this? Or is this a lot more complicated than I think this is? Simply trying every number from x + 1 to the upper limit is too inefficient. I will be using numbers up to 1,000,000,000,000, so efficiency is key here.

A: The paper below proves that it is very unlikely that this problem can be solved efficiently:

"Complexity of Inverting the Euler Function" by Scott Contini, Ernie Croot and Igor E. Shparlinski, published in Mathematics of Computation (doi, arxiv)


text:
Q: Passing Key/Value from a dictionary into a .config file c# I made the function below where I load the keys from two .config files into two dictionaries and later compare those dictionaries and change the value if they are different or I add a new key/value pair if it doesn't exist.
But now I need to add them again to the .config file replacing the older values and/or adding the new pair to it.
Can I do it such as if it was a .txt or is there a better way?
This is the function:
 public void UpdateClient(string FilePathOld, string FilePathNew)
        {
            Dictionary<string, string> Old = new Dictionary<string, string>();
            Dictionary<string, string> New = new Dictionary<string, string>();

            ExeConfigurationFileMap configOld = new ExeConfigurationFileMap();
            configOld.ExeConfigFilename = FilePathOld;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configOld, ConfigurationUserLevel.None);

            ExeConfigurationFileMap configNew = new ExeConfigurationFileMap();
            configNew.ExeConfigFilename = FilePathNew;
            Configuration config2 = ConfigurationManager.OpenMappedExeConfiguration(configNew, ConfigurationUserLevel.None);

            KeyValueConfigurationCollection settings = config.AppSettings.Settings;
            Old = settings.AllKeys.ToDictionary(key => key, key => settings[key].Value);
            KeyValueConfigurationCollection settings2 = config2.AppSettings.Settings;
            New = settings.AllKeys.ToDictionary(key => key, key => settings[key].Value);

            //Old = (config.GetSection("<appSettings>") as System.Collections.Hashtable)

            if (Old.Count == New.Count) // Require equal count.
            {

                foreach (var NewKey in New)
                {
                    string value;
                    if (Old.TryGetValue(NewKey.Key, out value))
                    {
                        if (value != NewKey.Value)
                        {
                            Old[NewKey.Key] = NewKey.Value;
                        }
                    }
                    else
                    {
                        Old.Add(NewKey.Key, NewKey.Value);
                    }
                }
            }

        }

Any help would be appreciated. Thank you

Is there a better way to do this rather than using dictionaries? A
  more "direct" way ?

A: public void UpdateService(string FilePathOld, string FilePathNew, string LatestVersion)
        {
                Dictionary<string, string> Old = new Dictionary<string, string>();
                Dictionary<string, string> New = new Dictionary<string, string>();

                if (ExisteFicheiro(FilePathNew) == true && ExisteFicheiro(FilePathOld) == true)
                {
                    ExeConfigurationFileMap configOld = new ExeConfigurationFileMap();
                    configOld.ExeConfigFilename = FilePathOld;
                    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configOld, ConfigurationUserLevel.None);

                    ExeConfigurationFileMap configNew = new ExeConfigurationFileMap();
                    configNew.ExeConfigFilename = FilePathNew;
                    Configuration config2 = ConfigurationManager.OpenMappedExeConfiguration(configNew, ConfigurationUserLevel.None);

                    KeyValueConfigurationCollection settings = config.AppSettings.Settings;
                    Old = settings.AllKeys.ToDictionary(key => key, key => settings[key].Value);
                    KeyValueConfigurationCollection settings2 = config2.AppSettings.Settings;
                    New = settings2.AllKeys.ToDictionary(key => key, key => settings2[key].Value);

                    foreach (var NewKey in New)
                    {
                        string value;
                        if (Old.TryGetValue(NewKey.Key, out value))
                        {
                            if (value != NewKey.Value)
                            {
                                //if (ExistsKey(NewKey.Key, false) == true)
                                Old[NewKey.Key] = NewKey.Value;

                            }
                        }
                        else
                        {
                            Old.Add(NewKey.Key, NewKey.Value);
                        }
                    }

                    foreach (var NewKey in Old)
                    {
                        string key = NewKey.Key;
                        string value = NewKey.Value;
                        if (config.AppSettings.Settings[key] != null)
                        {
                            config.AppSettings.Settings[key].Value = value;
                            if (key == "Version")
                                config.AppSettings.Settings[key].Value = LatestVersion;
                        }
                        else
                        {
                            config.AppSettings.Settings.Add(key, value);

                        }
                        if (config.AppSettings.Settings["Version"] == null)
                        {
                            config.AppSettings.Settings.Add("Version", LatestVersion);
                        }

                    }
                    config.Save();
                }
                else
                {
                    Erro NovoErro = new Erro();
                    Global.Erro = "O ficheiro \"OrcaService.exe.config\" ou o ficheiro \"Orca.exe.config\" não existem nos caminhos especificados!";
                }

        }

Done some work afterwords and this code works like a charm


text:
Q: printing delimiters in c language I am using strtok().But i want to print corresponding delimiters also as we do using StringTokenizer in Java.Is there any function which provides this functionality(printing delimiters) ?

A: Based on OP's comments, tokenization is not what is actually desired. You want to use strstr(), not strtok(). That will tell you if the string is present, and then you can use strcpy() and strcat() as appropriate.
Please note, the "n" versions of these methods, i.e. strncpy and strncat, are safer -- less likely to crash due to buffer overrun.

A:
i want to print corresponding delimiters also as we do using StringTokenizer in Java

Java's StringTokenizer doesn't return delimeters.
In any case, there is no such function in C. You'll have to write one (using strchr, etc.)

A: How about using glib?
It seems
http://library.gnome.org/devel/glib/2.26/glib-String-Utility-Functions.html#g-strsplit
is exactly what you're looking for.


text:
Q: How do find out if there is a full-screen app running on a specific NSScreen In Cocoa/AppKit, given a screen from [NSScreen screens], how can I find out if there's a full-screen app running on that specific screen? I'm mostly interested in apps that use the Cocoa APIs for full-screen, but if there's a solution that also encompasses other types of full-screen apps, even better. The solution needs be able to pass Mac App Store approval.
My specific use case involves a menu bar app (NSStatusItem) and figuring out whether or not a menubar is shown at all on [NSScreen mainScreen] in order to allow a global keyboard shortcut to show either a popover positioning on the status item (if it's visible) or a floating window if there's no visible status item.
NSScreens themselves don't seem to expose any information about windows/apps, and NSRunningApplication doesn't expose this information either.
Are there perhaps Carbon APIs for finding this out? For example, if I have a list of windows, I could iterate through them and see if any window frames match the screens' frame exactly. On the other hand, there might be apps that have a frame like that but run underneath other apps (like the Backdrop app, https://itunes.apple.com/us/app/backdrop/id411461952?mt=12), so an approach like this would need to look at window levels.

A: You can try the CGWindowList API, such as CGWindowListCopyWindowInfo().
If you just want to know if the menu bar is showing, you should be able to check -[NSApplication currentSystemPresentationOptions] for NSApplicationPresentationAutoHideMenuBar or NSApplicationPresentationHideMenuBar. That method can also tell you if the active app is in Cocoa full-screen mode (NSApplicationPresentationFullScreen).

A: Here's a solution based on CGWindowListCopyWindowInfo in Swift.
func fullScreenWindows(fullScreen: Bool) -> [CGWindowID] {
    var winList: [CGWindowID] = []
    // if you want to get the windows in full screen, you MUST make sure the option excluding 'optionOnScreenOnly'
    let option: CGWindowListOption = fullScreen ? .excludeDesktopElements : [.excludeDesktopElements, .optionOnScreenOnly]
    guard let winArray: CFArray = CGWindowListCopyWindowInfo(option, kCGNullWindowID) else {
        return winList
    }
    for i in 0..<CFArrayGetCount(winArray) {

        // current window's info
        let winInfo = unsafeBitCast(CFArrayGetValueAtIndex(winArray, i), to: CFDictionary.self)

        // current window's bounds
        guard let boundsDict = (winInfo as NSDictionary)[kCGWindowBounds],
            let bounds = CGRect.init(dictionaryRepresentation: boundsDict as! CFDictionary) else {
            continue
        }

        // to check the window is in full screen or not
        guard __CGSizeEqualToSize(NSScreen.main!.frame.size, bounds.size) else {
            continue
        }

        // current window's id
        guard let winId = (winInfo as NSDictionary)[kCGWindowNumber] as? CGWindowID,
            winId == kCGNullWindowID else {
            continue
        }

        winList.append(winId)
    }
    return winList
}

A: Here's a solution based on CGWindowListCopyWindowInfo, as Ken Thomases suggested in his answer:
- (BOOL)fullScreenAppPresentOn:(NSScreen *)screen
{
    // Get all of the visible windows (across all running applications)
    NSArray<NSDictionary*> *windowInfoList = (__bridge_transfer id)CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);

    // For each window, see if the bounds are the same size as the screen's frame
    for (int windowInfoListIndex = 0; windowInfoListIndex < (int)windowsInfoList.count; windowInfoListIndex++)
    {
        NSDictionary *windowInfo = windowInfoList[windowInfoListIndex];

        CFDictionaryRef windowInfoRef = (__bridge CFDictionaryRef) windowInfo[(__bridge NSString *)kCGWindowBounds];
        CGRect windowBounds;
        CGRectMakeWithDictionaryRepresentation(windowInfoRef, &windowBounds);

        if (CGRectEqualToRect([screen frame], windowBounds))
        {
            return YES;
        }
    }

    return NO;
}


text:
Q: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ml9eeocq I want to simply install a package named cpickle with pip3 but after running the command below:
sudo pip3 install cpickle

I got the following error:
Collecting cpickle
Downloading cpickle-0.5.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.4/tokenize.py", line 438, in open
    buffer = _builtin_open(filename, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/pip-build-cf2kl13q/cpickle/setup.py'

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-cf2kl13q/cpickle/

I've already read these links :
stackoverflow-1
stackoverflow-2
github
and so many others from the other communities but non of them worked for me.
Is it an unsolvable problem ?If it's not , then how can I solve the problem ?
I'm using virtualenv.


text:
Q: C++: Optimized list Some intensive profiling of my code revealed that a it spends a lot of time allocating space for vectors.
For Most of these vectors the size is known in advance so I call reserve() to pre-allocate the space.
For most of these vectors, the size is almost always very small - like 4 or 5 elements but on rare occasions it can be pretty large.
One additional optimization I thought about is to create my own container OptimizedList<T,N> . An instance of this object contains in itself N instances of T as a plain array and if the user tries to add more than N items, it starts using dynamic allocation for the extra items.
Is there a known implementation of this?

A: How about Qt's stack based variable length array?
Looks like the perfect match for your use case, mostly small arrays, which will be allocated on the stack (the fastest allocation, just a pair of add / sub instructions on a pointer)
for small arrays, and on the heap for large ones.
It does however waste space.

A: I would consider using std::vector with a custom allocator optimized for 4-5 elements (pulling those from a pool) as the simplest and most viable solution. This is also the only solution that I'd expect to actually give a net benefit.
Using a std::deque probably does not help, although it may seem that way from a textbook point of view. It might actually hurt. Deques reduce the overhead of copying data from O(n) to O(1), but they are not magically allocation-free. On the contrary, they may cause a lot more allocations than using a vector would.
Deques are usually implemented either as vector of vectors or as circular buffer. In the latter case, you have exactly the same reallocation overhead as with using std::vector except you can't mitigate it by calling reserve(), and in the former case you have two allocations where you would otherwise only have one.
Embedding the first few objects directly into your custom vector class or into an on-stack vararray as in Bgie's answer is very tempting, and this would indeed be a great solution for not too many not too large vectors.
However, since you are having a performance problem from creating those vectors, one can conclude that you are not using just 5 or 10 vectors, but many of them (otherwise it wouldn't really matter, it wouldn't be measurable!).  Which means putting data on the stack would likely cause an eventual stack overflow.
This may however be a good solution if all your vectors are heap-allocated anyway. There is no real difference whether you allocate a few hundred bytes more when allocating the container itself, and there is no risk overflowing the stack. So in that case, you'd effectively save one allocation.

A: Because most of your containers are small and rare containers get many elements, i'd prefer std::deque. This can help you to avoid unnecessary reallocations at low price. It does not have the reserve() method, but since most containers are small, i think its ok.
More important, you should check your object type, which is contained in those containers. I think the bottleneck is not reallocate itself, but copy/destroy part of it. I suspect that "container's values" copy constructors and/or destructors are "heavy" enough. Its very time-consuming to copy N elements and then destroy old N elements when constructors/destructors are  too complicated.
As last optimization, i'd suggest to use a memory pool/allocator to reduce underlying malloc/realloc/free calls.