text:
Q: error: extern declaration of 'i' follows declaration with no linkage In the following program, I thought that extern int i; will change the following i to refer to the i defined outside main:
#include <stdio.h>

extern int i=1; // warning: 'i' initialized and declared 'extern'

int main()
{
    int i=2;
    printf("%d\n", i);
    extern int i; // error: extern declaration of 'i' follows declaration with no linkage
    printf("%d\n", i);
    return 0;
}

What is the reason of the "error: extern declaration of 'i' follows declaration with no linkage", where "declaration with no linkage" refers to int i=2;?
After I remove int i=2 in main,

*

*the error is gone,

*the warning "warning: 'i' initialized and declared 'extern'" on extern int i=1; also disappear . Why is that?

Thank you for explanations!

A: #include <stdio.h>

int i=1;  // external variable

int main()
{
    int i=2;            // local variable
    printf("%d\n", i);  // print local variable i==2

    {
    extern int i;       // point to external variable
    printf("%d\n", i);  // print external variable i==1
    }

    return 0;
}

A: Once you define a variable named i inside your main function, the i at file scope is masked and cannot be accessed (unless you have its address).
When you later add the declaration extern int i, this conflicts with the local variable named i at the same scope since locals can't have external linkage.  It does not give you access to the global i.
When you remove the local i, the extern int i declaration matches up with the definition at file scope, so there is no error.  As for the warning on extern int i=1;, that did not go away for me on gcc 4.1.2, so that depends on the compiler.

A: Question: What is the reason of the "error: extern declaration of 'i' follows declaration with no linkage", where "declaration with no linkage" refers to int i=2;?
Answer: We do not need to use the extern keyword here on line 3 when it is a single file in a program and there is no other file in the same program or other location on the same file where the variable int i has its definition. There are two main reasons we can use extern keyword in C:
 1. When we want to declare a variable explicitly/globally but without its definition.
 2. To make the variable globally visible from any other file in a multi-file program or other location of the same file (see Ihdina's exmaple for this scenario).
Compiling your code on my system I get the following error,
error: extern declaration of 'i' follows non-extern declaration .
which totally makes sense that the compiler detects the extern on line 9 as a duplicate declaration of the same variable int i on line 7.
Question: After I remove int i=2 in main,
the error is gone,
the warning "warning: 'i' initialized and declared 'extern'" on extern int i=1; also disappear . Why is that?
Answer: After removing the int i=2; the error was gone on my system but still I have the following warning message:
warning: 'extern' variable has an initializer [-Wextern-initializer]
Basically my system (Apple LLVM version 8.1.0 (clang-802.0.42)) does not like the explicit initialization with extern keyword. So, you should modify your code as per Ihdina's answer which compiles without error.


text:
Q: Data isn't showing in datatable - PHP I'm using  https://datatables.net for my Admin panel. I need help, When I try to display user data on the table it shows nothing. Everything is working in the Inspect, it just does not come out. Why?
Here is the code of app-user-list.js
  if (dtUserTable.length) {
    dtUserTable.DataTable({
        "ajax": {
            "url": assetPath + 'data/user-list.php',
            "type": "POST"
        }, // JSON file to add data
      columns: [
        // columns according to JSON
        { data: 'responsive_id' },
        { data: 'full_name' },
        { data: 'email' },
        { data: 'role' },
        { data: 'current_plan' },
        { data: 'status' },
        { data: '' }
      ],
      columnDefs: [
        {
          // For Responsive
          className: 'control',
          orderable: false,
          responsivePriority: 2,
          targets: 0
        },
        {
          // User full name and username
          targets: 1,
          responsivePriority: 4,
          render: function (data, type, full, meta) {
            var $name = full['full_name'],
              $uname = full['username'],
              $image = full['avatar'];
            if ($image) {
              // For Avatar image
              var $output =
                '';
            } else {
              // For Avatar badge
              var stateNum = Math.floor(Math.random() * 6) + 1;
              var states = ['success', 'danger', 'warning', 'info', 'dark', 'primary', 'secondary'];
              var $state = states[stateNum],
                $name = full['full_name'],
                $initials = $name.match(/\b\w/g) || [];
              $initials = (($initials.shift() || '') + ($initials.pop() || '')).toUpperCase();
              $output = '' + $initials + '';
            }
            var colorClass = $image === '' ? ' bg-light-' + $state + ' ' : '';
            // Creates full output for row
            var $row_output =
              '
' +
              '
' +
              '
' +
              $output +
              '
' +
              '
' +
              '
' +
              '' +
              $name +
              '' +
              '@' +
              $uname +
              '' +
              '
' +
              '
';
            return $row_output;
          }
        },
        {
          // User Role
          targets: 3,
          render: function (data, type, full, meta) {
            var $role = full['role'];
            var roleBadgeObj = {
              Subscriber: feather.icons['user'].toSvg({ class: 'font-medium-3 text-primary mr-50' }),
              Author: feather.icons['settings'].toSvg({ class: 'font-medium-3 text-warning mr-50' }),
              Maintainer: feather.icons['database'].toSvg({ class: 'font-medium-3 text-success mr-50' }),
              Editor: feather.icons['edit-2'].toSvg({ class: 'font-medium-3 text-info mr-50' }),
              Admin: feather.icons['slack'].toSvg({ class: 'font-medium-3 text-danger mr-50' })
            };
            return "" + roleBadgeObj[$role] + $role + '';
          }
        },
        {
          // User Status
          targets: 5,
          render: function (data, type, full, meta) {
            var $status = full['status'];

            return (
              '' +
              statusObj[$status].title +
              ''
            );
          }
        },
        {
          // Actions
          targets: -1,
          title: 'Actions',
          orderable: false,
          render: function (data, type, full, meta) {
            return (
              '
' +
              '' +
              feather.icons['more-vertical'].toSvg({ class: 'font-small-4' }) +
              '' +
              '
' +
              '' +
              feather.icons['file-text'].toSvg({ class: 'font-small-4 mr-50' }) +
              'Details' +
              '' +
              feather.icons['archive'].toSvg({ class: 'font-small-4 mr-50' }) +
              'Edit' +
              '' +
              feather.icons['trash-2'].toSvg({ class: 'font-small-4 mr-50' }) +
              'Delete
' +
              '
' +
              '
'
            );
          }
        }
      ],
      order: [[2, 'desc']],
      dom:
        '<"d-flex justify-content-between align-items-center header-actions mx-1 row mt-75"' +
        '<"col-lg-12 col-xl-6" l>' +
        '<"col-lg-12 col-xl-6 pl-xl-75 pl-0"<"dt-action-buttons text-xl-right text-lg-left text-md-right text-left d-flex align-items-center justify-content-lg-end align-items-center flex-sm-nowrap flex-wrap mr-1"<"mr-1"f>B>>' +
        '>t' +
        '<"d-flex justify-content-between mx-2 row mb-1"' +
        '<"col-sm-12 col-md-6"i>' +
        '<"col-sm-12 col-md-6"p>' +
        '>',
      language: {
        sLengthMenu: 'Show _MENU_',
        search: 'Search',
        searchPlaceholder: 'Search..'
      },
      // Buttons with Dropdown
      buttons: [
        {
          text: 'Add New User',
          className: 'add-new btn btn-primary mt-50',
          attr: {
            'data-toggle': 'modal',
            'data-target': '#modals-slide-in'
          },
          init: function (api, node, config) {
            $(node).removeClass('btn-secondary');
          }
        }
      ],

And more, but this is for table.
This is code in Users/index.blade.php

@section('title')
Users
@endsection

@section('content')

                                        User
                                        Email
                                        Role
                                        Plan
                                        Status
                                        Actions

@endsection

This is code in data/user-list.php

 /*
  * DataTables example server-side processing script.
  *
  * Please note that this script is intentionally extremely simple to show how
  * server-side processing can be implemented, and probably shouldn't be used as
  * the basis for a large complex system. It is suitable for simple use cases as
  * for learning.
  *
  * See http://datatables.net/usage/server-side for full details on the server-
  * side processing requirements of DataTables.
  *
  * @license MIT - http://datatables.net/license_mit
  */

 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  * Easy set variables
  */

 // DB table to use
 $table = 'users';

 // Table's primary key
 $primaryKey = 'id';

 // Array of database columns which should be read and sent back to DataTables.
 // The `db` parameter represents the column name in the database, while the `dt`
 // parameter represents the DataTables column identifier. In this case object
 // parameter names
 $columns = array(
     array( 'db' => 'id', 'dt' => 'responsive_id' ),
     array( 'db' => 'id',  'dt' => 'id' ),
     array( 'db' => 'name',   'dt' => 'name' ),
     array( 'db' => 'lastname',     'dt' => 'full_name' ),
     array( 'db' => 'email',     'dt' => 'email' ),
     array( 'db' => 'birthday',     'dt' => 'current_plan' ),
     array( 'db' => 'gender',     'dt' => 'status' ),
     array( 'db' => 'image',     'dt' => 'avatar' ),
     array(
         'db'        => 'role',
         'dt'        => 'role',
     ),
     array(
         'db'        => 'name',
         'dt'        => 'username',
     )
 );

 // SQL server connection information
 $sql_details = array(
     'user' => 'root',
     'pass' => '',
     'db'   => 'family_space',
     'host' => '127.0.0.1'
 );

 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  * If you just want to use the basic configuration for DataTables with PHP
  * server-side, there is no need to edit below this line.
  */

 require( 'ssp.class.php' );

 echo json_encode(
     SSP::simple( $_POST, $sql_details, $table, $primaryKey, $columns )
 );

This is photo:

I really need help. can I fix this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it a bad idea to just create a Text component that always translated its contents with react-i18next? In the process of translating a smallish RN app (50% done), I noticed that most of the strings on React Native are displayed via Text components. So I wrote the following class and used it instead of React Native's Text:
import {Text as RNText} from 'react-native';
import {useTranslation} from 'react-i18next';

export default ({children, style}) => {
  const {t} = useTranslation();
  if (Array.isArray(children)) {
    const translated = children.map((el) => t(el));
    return <RNText style={style}>{translated}</RNText>;
  }

  const translated = t(children);
  return <RNText style={style}>{translated}</RNText>;
};

This worked so well and was so pragmatic in my case that I wondered if its a bad idea - otherwise I feel like it would have been cited in the documentation as a good way to use react-i18next.
Am I missing something?

A: If this works well for you, good job! you should definitely keep using the component.
This usage is probably not documented in react-i18next for a variety of reason:

*

*It's good for a library to leave the users complete freedom over its usages. I would prefer the mainteners of react-i18next to focus on improving the translation aspect than using resource mainiting those kind of components;

*It's trivial for users to write such a component themselves supporting their specific use cases, as you did;

*Such a compoment does not handle all edge cases, so in your codebase there are probably some situations where you don't use the component but you still use Text in the good old way. Think about a string with some variables you need to pass to:
<Text>{t('key', { value: this.state.value })}</Text>

Many developer probably prefer to keep the little additional verbosity to repeat t() each time, in exchange of a better standard behaviour that suits all edge cases cases.


text:
Q: C# mailto: Throws Exception in .NET 6.0 This code works in C# .NET 4.6...
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "mailto:" + "info@mydomain.com" + "?subject=My Subject"+
                                    "&body=My Body";
proc.Start();

However, C# .NET 6.0 throws an exception:
System.ComponentModel.Win32Exception: 'An error occurred trying to start process 'mailto...
How am I supposed to launch the default mail client and populate the fields in C#/.NET 6.0?


text:
Q: "ConverterNotFoundException" in Spring boot JPA I want to get the SearchOutput data object by calling a query(@Query method) with natural joins of 3 tables. but when the query runs it shows an error.
I have tried to fetch the data in my spring boot controller class. But its not working because of the error
package com.example.mysqlproj.model;
import lombok.*;
public class SearchOutput {
    private String  hotel_name;
    private String room_type;
    private int price;

}

package com.example.mysqlproj.dao;
import com.example.mysqlproj.model.Room_Type;
import com.example.mysqlproj.model.SearchOutput;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.Collection;
import java.util.Date;
import java.util.List;

public interface RoomTypeDao extends CrudRepository<Room_Type,Integer> {

    @Query(value="select new SearchOutput(hotel_name , room_type,(price*(?4)*(?3)*(1.15))) from Room_type natural join Hotel natural join True_contract where  (?1 >= start_date and ?2 <= end_date and ?3 <=available_rooms and ?4<= max_adults )", nativeQuery = true)
    List<SearchOutput[]> checkHotelList(Date from, Date to, int rooms, int adults, int total_nights);

}

The Error:
No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.example.mysqlproj.model.SearchOutput]] with root cause

My target is to fetch a searchOutput object array when the query gets called.
Are there any solutions for this. Thanks in advance

A: The response type from the query is
List<Map<String, Object>> .
Please change the method return type to this.


text:
Q: ios audio unit how to get decibel directly How can I get decibel by audio unit directly rather than calculate use formula ?
I found occur error when I use formula to get decibel. So I want to exchange method get decibel.

A: There is no iOS Audio Unit API that directly returns decibels.  You have to calibrate each device and microphone against a known standard, and then adjust your formula to return the calibrated results.  Then feed a suitably sized vector of frequency weighted raw audio samples from Audio Unit callback buffers to a amplitude measurement algorithm.

A: The question is that I find audio unit data become abnormal from the data[512](the data size is 1024). So I don't handle these data and find the audio unit can work abnormality. Because we only use the data to calculate db.


text:
Q: How can passing data from ViewPagerAdapter to a different activity I add to my app ViewPager to display a set of images I get the image from database.It works fine but I need to work (Intent) to image.So where user click on image he should go to a new activity and see that picture in it.I searched for a solution and could not find the solution.
If anyone Knew the solution help me please.

public class ViewPagerAdapter extends PagerAdapter {

    private Context context;
    private LayoutInflater layoutInflater;
    private List<SliderUtils> sliderImg;
    private ImageLoader imageLoader;

    public ViewPagerAdapter(List sliderImg,Context context) {
        this.sliderImg = sliderImg;
        this.context = context;
    }

    @Override
    public int getCount() {
        return sliderImg.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {

        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.custom_layout, null);

        SliderUtils utils = sliderImg.get(position);

        ImageView imageView = (ImageView) view.findViewById(R.id.imageView);

        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
        imageLoader.get(utils.getSliderImageUrl(), ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher_round, android.R.drawable.ic_dialog_alert));

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(position == 0){
                    Toast.makeText(context, "Slide 1 Clicked", Toast.LENGTH_SHORT).show();
                } else if(position == 1){
                    Toast.makeText(context, "Slide 2 Clicked", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Slide 3 Clicked", Toast.LENGTH_SHORT).show();
                }

            }
        });

        ViewPager vp = (ViewPager) container;
        vp.addView(view, 0);
        return view;

    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        ViewPager vp = (ViewPager) container;
        View view = (View) object;
        vp.removeView(view);

    }
}

public class FoodFregmaent extends Fragment {

    ViewPager viewPager;
    LinearLayout sliderDotspanel;
    private int dotscount;
    private ImageView[] dots;

    RequestQueue rq;
    List<SliderUtils> sliderImg;
    ViewPagerAdapter viewPagerAdapter;

    String request_url = "http://===========sliedshow.php";

    public FoodFregmaent() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_food_fregmaent, container, false);

        rq = CustomVolleyRequest.getInstance(getContext()).getRequestQueue();

        sliderImg = new ArrayList<>();

        viewPager = (ViewPager) view.findViewById(R.id.viewPager);

        sliderDotspanel = (LinearLayout)view. findViewById(R.id.SliderDots);

        sendRequest();

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                for(int i = 0; i< dotscount; i++){
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.nonactive_dot));
                }

                dots[position].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.active_dot));

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

return view;

    }

    public void sendRequest(){

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, request_url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                for(int i = 0; i < response.length(); i++){

                    SliderUtils sliderUtils = new SliderUtils();

                    try {
                        JSONObject jsonObject = response.getJSONObject(i);
                        sliderUtils.setSliderImageUrl(jsonObject.getString("imageurl"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    sliderImg.add(sliderUtils);

                }

                viewPagerAdapter = new ViewPagerAdapter(sliderImg, getActivity());

                viewPager.setAdapter(viewPagerAdapter);

                dotscount = viewPagerAdapter.getCount();
                dots = new ImageView[dotscount];

                for(int i = 0; i < dotscount; i++){

                    dots[i] = new ImageView(getActivity());
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.nonactive_dot));

                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                    params.setMargins(8, 0, 8, 0);

                    sliderDotspanel.addView(dots[i], params);

                }

                dots[0].setImageDrawable(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.ic_launcher_background));

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        CustomVolleyRequest.getInstance(getContext()).addToRequestQueue(jsonArrayRequest);
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);
    }
    public class MyTimerTask extends TimerTask {

        @Override
        public void run() {

          getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if(viewPager.getCurrentItem() == 0){
                        viewPager.setCurrentItem(1);
                    } else if(viewPager.getCurrentItem() == 1){
                        viewPager.setCurrentItem(2);
                    } else {
                        viewPager.setCurrentItem(0);
                    }

                }
            });

        }
    }

}

public class SliderUtils {

    String imageurl;

    public String getSliderImageUrl() {
        return imageurl;
    }

    public void setSliderImageUrl(String imageurl) {
        this.imageurl = imageurl;
    }
}

Still I search about solution to it

A: You can add an Intent with a String that contains the image URL into your view.setOnClickListener within the instantiateItem() of the ViewPager
@Override
public Object instantiateItem(ViewGroup container, final int position) {

    // ... Other code is omitted

    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(v.getContext(), Activity2.class); // Change the name of the other activity
            intent.putExtra("url", sliderImg.get(position).getSliderImageUrl()); // add the image URL to  the other activity

        }
    });

And at the target activity, receive the url with
String url = getIntent().getStringExtra("url")


text:
Q: Nullable foreign key with composite key So, first, i must apply symfony to an existing (and old) database.
It's not very easy and some relationship are pretty complex to implement.
My problem is, I have a many -to- One relationship with a composite key
In one side, the id_group is defined by default but the id (within the group) can be null
When i try to get a movement with a null id, symfony tell me

Missing value for primary key id...

The relationship is defined like this.
ACTION :
/**
* @ORM\ManyToOne(targetEntity="Gestion\CodifBundle\Entity\Codif",inversedBy="ActionsByOrigin")
* @ORM\JoinColumns({
*                   @ORM\JoinColumn(name="ref_origin", referencedColumnName="id"),
*                   @ORM\JoinColumn(name="ref_group_origin", referencedColumnName="id_group")
*                   })
*/
private $origin;

CODIF
/**
* inverse Side
* @Type("ArrayCollection<Gestion\SiteBundle\Entity\comAction>")
* @ORM\OneToMany(targetEntity="Gestion\SiteBundle\Entity\comAction" , mappedBy="origin")
*/
private $ActionsByOrigin;

I have made a mistake ? Or it's impossible to do like that ?


text:
Q: How to split time into 10 min interval and make it as a separate column using Python I am working on a data set that has epoch time. I want to create a new column which splits the time into 10 mins time interval.
Suppose
timestamp       timeblocks
5:00            1
5:02            1
5:11            2
How can i achieve this using python.
I tried resampling but i cannot able further process.

A: I agree with the comments, you need to provide more.  After guessing what you're looking for, you may want histograms where intervals are known as bins.  You wrote "10 mins time interval" but your example doesn't show 10 mins.
Python's Numpy and matplotlib have histograms for epochs.
Here's an SO answer on histogram for epoch time.

A: I'm guessing here, but I believe you are trying to 'bin' your time data into 10 min intervals.
Epoch or Unix time is represented as time in seconds (or more commonly nowadays, milliseconds).
First thing you'll need to do is convert each of your epoch time to minutes.
Assuming you have a DataFrame and your epoch are in seconds:
df['min] = df['epoch'] // 60

Once that is done, you can bin your data using pd.cut:
df['bins'] = pd.cut(df['min'], bins=pd.interval_range(start=df['min'].min()-1, end=df['min'].max(), freq=10))

Notice that -1 on start is to shift the first bin to beginning of each 10 min interval.
You'll have your 'bins', you can rename them to your liking and you can groupby them.
The solution may not be perfect, but it will possibly get you on the right track.
Good luck!


text:
Q: codeigniter create response array object I have the code below, but the result of the json response doesn't match
public function tes_get(){
        $kode= $this->M_mymodel->tbl_kode('302'); // row
        $res = array();
        foreach ($kode as $key=> $value) {
            $win = $this->M_mymodel->db_aa('302'); //row_array
            $res = $this->M_mymodel->db_bb('302','LOSE'); //row_array
            $res['data'][] = array(
                'win' => $win['menang'],
                'lose' =>$res['kalah']
            );
        }
        $response =  $this->set_response($res,200);
    }

Below is the result of the response from the code I made above
{
    "data": [
        {
            "win": "2",
            "lose": "11"
        }
    ]
}

How to make json response like below?
{
    "data": [
        {
            "win": "2",
        }
        {
            "lose": "11"
        }
    ]
}

A: You can try :
$res['data'][] = array(
    array('win' => $win['menang']),
    array('lose' =>$res['kalah'])
);


text:
Q: wp-admin produces a 302 redirect to itself I'm running Wordpress (v3.5.2) in network mode.
Any of the sites which try to access /wp-admin produce a browser error saying there is a redirect loop.  A redirect checker tool says the page returns a 302 temporary redirect to the same URL.
I have uploaded a default .htaccess file and the same thing happens.
In cPanel, I have checked Domains > Redirects, and there is no such redirect listed.
I have renamed /plugins to /plugins2, and the issue remains.
In the wp_options table, the site_URL is set to www.example.com, which is correct.  This matches the DOMAIN_CURRENT_SITE parameter in wp-config.
Any ideas?

A: I ended up uploading fresh copies of /wp-admin & /wp-includes, as well as the wp files in the root / directory, which resolved the problem.

A: I had this problem as well, it turned out to be a hosting issue with the permissions of some of my files being chmod 0664 and the host not like group to be writable. I changed the files to 0644 and everything worked. There is never a clear solution to this problem, but that may help for people looking for other solutions.

A: There is a plugin called "change-wp-admin-login" - check that or move it out of the plugins folder temporarily


text:
Q: Homomorphisms between matrix groups I was having a discussion with my friend, who is a physics major, but nevertheless enjoys taking math courses. He believes that a non-trivial homomorphism as I describe below cannot exist. My gut tells me that that is not true, but I am not able to find an example.
Could anyone define a group homomorphism from a matrix group that is a subgroup of $GL_n(\mathbb{Z}[x, x^{-1}])$ to a matrix group that is a subgroup of $GL_n(\mathbb{Z})$?

A: There exists a surjective homomorphism $GL_n(\mathbb{Z}[x,x^{-1}])\rightarrow GL_n(\mathbb{Z})$ given by the evaluation of $x$ at $1$, i.e. given a matrix $A\in GL_n(\mathbb{Z}[x,x^{-1}])$ whose coefficients are integral polynomials $A_{ij}$ of $x$ and $x^{-1}$, one maps $A$ to the matrix $[a_{ij}]$ with $a_{ij}=A_{ij}(1,1)$.

Now since any homomorphism $GL_n(\mathbb{Z}[x,x^{-1}])\rightarrow GL_n(\mathbb{Z})$ is defined by the image of $x$ in $GL_n(\mathbb{Z})$, the real question is:
What are those $a\in GL_n(\mathbb{Z})$ such that $x\rightarrow a$ is extended to a homomorphism $GL_n(\mathbb{Z}[x,x^{-1}])\rightarrow GL_n(\mathbb{Z})$?
My guess: all elements of $GL_n(\mathbb{Z})$.


text:
Q: Template cast operator C++ I am trying to make a little wrapper class such as
template <typename T>
class EdgeTriggeredState

{

public:
    void Tick()
    {
        oldData = newData;
    }

    EdgeTriggeredState& operator =(const T& v)
    {
        newData = v;
        return *this;
    }

//  T& operator = (void)
//  {
//      return oldData;
//  }

//  T& operator T()
//  {
//      return oldData;
//  }

private:
    T oldData;
    T newData;
};

Basically I want to be able to directly assign to a variable of type T the value wrapped by the class. I have tried implementing both an assignment (to type T) operator and a cast operator to type T. I am a bit rusty on my C++ as I have been working solely in C. Is there a way to go about implementing this without creating a named getter method?
When I uncomment the first implementation attempt I get error

"../EdgeTriggeredState.h:19:21: error: 'T& EdgeTriggeredState::operator=()' must take exactly one argument"

When I uncomment the second implementation (and comment out the first) I get error:

"../EdgeTriggeredState.h:24:16: error: return type specified for 'operator T'"

A: When you write an operator T, the return type is implicit, so your code should look something like:
template <typename T>
class DumbWrapper {
    T oldData;
    T newData;
public:
    DumbWrapper& operator = (const T& val) {
        newData = val;
        return *this;
    }

    operator T() {
        return oldData;
    }
};

[Also note the semicolon at the end, and the fact that the constructor and conversion operator were probably intended to be public.]


text:
Q: Не подключить MySql в React Решил написать приложение на React. Мне нужно получить данные из бд mysql.
Есть код:
const mysql = require("mysql");
const connection = mysql.createConnection({
        host: "localhost",
        user: "user",
        database: "database",
        password: "password"
      });
connection.connect(function(err){
        if (err) {
          return console.error("Ошибка: " + err.message);
        }
        else{
          console.log("Подключение к серверу MySQL успешно установлено");
        }
     });

connection.query("SELECT * FROM users;",
      function(err, results, fields) {
        console.log(err);
        console.log(results);
        console.log(fields);
    });
    connection.end(function(err) {
        if (err) {
          return console.log("Ошибка: " + err.message);
        }
        console.log("Подключение закрыто");
      });

На что я получил ошибку:
TypeError: Net.createConnection is not a function

Что я делаю не так?
Доп. вопрос - Как скрыть пароль от бд?

A: Реакт - это фронтэнд, то есть всё, что доступно любому пользователю, поэтому подключение к БД там быть не может, иначе любой пользователь сможет воспользоваться вашим паролем.
Вам нужно создать бэкэнд и уже там подключаться к БД. Из реакта же вы будете делать запросы к бэкэнду.
Если не хотите создавать бэкэнд, воспользуйтесь next.js - там есть встроенный бэкэнд.


text:
Q: Doxygen: wrong function name in the documentation (C) I've got functions defined as follows:
#define FUNC(rettype, memclass) rettype

/// @brief a function.
/// @param param a function parameter.
FUNC(void, PUBLIC_CTX) my_fun1(int* param);

/// @brief a function.
FUNC(int, PUBLIC_CTX) my_fun2(void);

but when generating doxygen documentation all the functions are named as FUNC instead of my_fun1, my_fun2.
Is there a way to make doxygen take the right function name?


text:
Q: perl sort multiple arryrefs of date time strings I want to sort an arrayref %results (Time-strings, from old to new), it has multiple keys but I just posted one key to show how it looks like:
'Ende Monatswechsel P-Konten' => [
                                         '17.02.2018 05:17:39',
                                         '14.02.2018 04:28:11',
                                         '23.02.2018 03:17:17',
                                         '22.02.2018 03:39:20',
                                  ]

I am expecting:
    'Ende Monatswechsel P-Konten' => [
                                         '14.02.2018 04:28:11',
                                         '17.02.2018 05:17:39',
                                         '22.02.2018 03:39:20',
                                         '23.02.2018 03:17:17',
                                  ]

Does any know how to do this?
I tried:
my $columns = map [ $_, sort{$a <=> $b} @{ $results{$_} } ], keys %results;
but it doesn't work.
Thanks in advance.
My code looks like this:
while(my $line=<F>) {
    #- Info: 19.02.2018 00:01:01 --- Start Tageswechsel-CoBa ---
    #- Info: 27.11.2018 04:16:42 --- Ende Tageswechsel-CoBa ---
            if ($line=~ /(\d\d\.\d\d\.\d\d\d\d \d\d:\d\d:\d\d) --- (.+? Tageswechsel-CoBa) -.*\s*$/)
            {
                    ($timestamp, $action) = ($1,$2);
            }
            if ( !defined $filter{$action}{$timestamp} ) {
                    push @{$results{$action}}, $timestamp;
                    $filter{$action}{$timestamp} = 1;
            }
}

print Dumper(\%results) outputs:
'Start Tageswechsel-CoBa' => [
                                '17.02.2018 05:12:13',
                                '20.02.2018 04:23:16',
                                '22.02.2018 03:12:46',
                                '23.02.2018 03:34:28',
                                '27.02.2018 03:41:25',
                                '02.03.2018 03:32:26',
            ],
'Ende Tageswechsel-CoBa' => [
                                    '17.02.2018 05:20:01',
                                    '19.02.2018 06:01:02',
                                    '20.02.2018 04:29:44',
                                    '22.02.2018 03:19:04',
                                    '23.02.2018 03:40:52',
                                    '26.02.2018 06:01:26',
            ]
            };

A: Something like this would work:
#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $data = [
  '17.02.2018 05:17:39',
  '14.02.2018 04:28:11',
  '23.02.2018 03:17:17',
  '22.02.2018 03:39:20',
];

my @sorted = sort {
  my @a = split /[\. ]/, $a;
  my @b = split /[\. ]/, $b;
  return (
    $a[2] <=> $b[2] or  # year
    $a[1] <=> $b[1] or  # month
    $a[0] <=> $b[0] or  # day of month
    $a[3] cmp $b[3]     # time
  );
} @$data;

say Dumper @sorted;

I'm splitting each value into chunks and then sorting them from largest chunk to smallest. Note that as the time is a string, not a number I use cmp instead of <=>.
This is slightly inefficient, as I'm re-splitting each data item several times. If that's a problem, then you could look at something like a Schwartzian Transform.
But the best solution to this would be to get a sortable timestamp in the first place. If your dates were YYYY.MM.DD HH:MM:SS, then you could just do a simple string sort.
Update: My output is
$ perl sortdate
$VAR1 = '14.02.2018 04:28:11';
$VAR2 = '17.02.2018 05:17:39';
$VAR3 = '22.02.2018 03:39:20';
$VAR4 = '23.02.2018 03:17:17';

Update 2: I've edited my code to make it more like your example. Hope this helps.
#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my %results = (
  'Ende Monatswechsel P-Konten' => [
    '17.02.2018 05:17:39',
    '14.02.2018 04:28:11',
    '23.02.2018 03:17:17',
    '22.02.2018 03:39:20',
  ]
);

foreach my $k (keys %results) {
  my @sorted = sort {
    my @a = split /[\. ]/, $a;
    my @b = split /[\. ]/, $b;
    return (
      $a[2] <=> $b[2] or  # year
      $a[1] <=> $b[1] or  # month
      $a[0] <=> $b[0] or  # day of month
      $a[3] <=> $b[3]     # time
    );
  } @{ $results{$k} };

  $results{$k} = \@sorted;
}

say Dumper \%results;

And the output...
$VAR1 = {
          'Ende Monatswechsel P-Konten' => [
                                             '14.02.2018 04:28:11',
                                             '17.02.2018 05:17:39',
                                             '22.02.2018 03:39:20',
                                             '23.02.2018 03:17:17'
                                           ]
        };

A: Splitting the strings and comparing the parts is appropriate for sorting many types of "multipart" values, however since you are dealing with datetimes, you can use the core module Time::Piece to turn the strings into datetime objects which can be compared using the <=> operator.
Time::Piece provides the strptime method, which parses a date string into a Time::Piece object using a format string. Time::Piece objects can be compared using numerical comparison operators.
use v5.10;
use strict
use warnings;
use Time::Piece;

my @vals = (
    '17.02.2018 05:17:39',
    '14.02.2018 04:28:11',
    '23.02.2018 03:17:17',
    '22.02.2018 03:39:20',
);

say for sort {dt($a) <=> dt($b)} @vals;

###

sub dt {
    my $str = shift;
    return Time::Piece->strptime($str,'%e.%m.%Y %H:%M:%S')
}

A: I actually used Dave's approach now (since I don't have the module Time::Piece installed) slightly different but it works now, not sure though about the efficency:
my @array;
my @sorted;
my %aref_n;

for my $key ( keys %results ) {
    for my $i (0..$#{ $results{$key} }) {
            push @array, $results{$key}[$i];
    }

    @sorted = sort {
            my @a = split /[\. ]/, $a;
            my @b = split /[\. ]/, $b;
            return (
                    $a[2] <=> $b[2] or
                    $a[1] <=> $b[1] or
                    $a[0] <=> $b[0] or
                    $a[3] cmp $b[3]
                    );
            } @array;

    $aref_n{$key} = [ @sorted ];
    @array=();

}


text:
Q: Sum different fields using aggregation in MongoDB I have a document schema in a test collection like this:
{
  "_id" : NumberLong("A unique number"),
  "text" : {
         "characters_map" : {
                          "a" : 4,
                          "f" : 3,
                          "b" : 6,
                            ...
                          "o" : 3
                         }
            ...
         }
    ...
}

I want to count the sum of each character in the whole collection. I tried using the aggregation framework, but it doesn't seem I do it correct.
I began by calculating each character separately ( i.e the 'a'), but with no luck. My best approach is:
> db.test.aggregate([
    { "$group" : {
         _id : { a_count : "$text.characters_map.a" },
         counter : { "$sum" : "$text.characters_map.a" }
      }
    }
  ])

with a_count representing the name of the id.
which results to:
{ "_id" : { "a_map" : 8 }, "counter" : 8 }
{ "_id" : { "a_map" : 5 }, "counter" : 5 }
{ "_id" : { "a_map" : 7 }, "counter" : 21 }
 ...

Not false entirely, but not what I want. These results mean I have 1 document with a field of: { "a" : 8, ... }, another 1 document with: { "a" : 5, ... } and 3 documents with: { "a" : 7, ... }.
Is there any way to group these fields together at "a" level? Is my approach completely wrong?

A: You have to change your structure to something like below.(Preferred)
[{
  "text" : { "characters_map" : [{"k":"a", "v":4},  {"k":"b", "v":8},  {"k":"c", "v":5}, {"k":"d", "v":4  }]  }
}]

You can use aggregation the way you tried in your post.
db.test.aggregate([
 {$unwind:"$text.characters_map"},
 {$group:{_id:"$text.characters_map.k", counter:{$sum:"$text.characters_map.v"}}}
 ])

This is the solution if you can't change your structure.
You can use 3.4.4 version and use $objectToArray & $arrayToObject to switch between dynamic keys and label value pair.
Stage 1: Convert the dynamic characters_map keys into label value pair.
Stage 2 & 3: $unwind & $group on the characters and sum their counts.
Stage 4 & 5: Group back the output from last grouping into array of key value pairs followed by $arrayToObject to convert the key value pairs into dynamic keys.
db.test.aggregate([
 {$addFields: {"text.characters_map": {$objectToArray: "$text.characters_map"}}},
 {$unwind:"$text.characters_map"},
 {$group:{_id:"$text.characters_map.k", counter:{$sum:"$text.characters_map.v"}}},
 {$group:{_id:null, arraykeyval:{$push:{k:"$_id", v:"$counter"}}}},
 {$project:{result: {$arrayToObject:"$arraykeyval"}}}
 ])


text:
Q: Passing multiple POJO to restful api using Jersey Pojo mapping feature and Jquery Currently we have the Pojo Mapping feature enabled as below:
<servlet-class>
com.sun.jersey.spi.spring.container.servlet.SpringServlet
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.rest.services</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>

Rest method is as follows
    @POST
        @Path("/test")
        @Produces(MediaType.APPLICATION_JSON)
        public Response addSomething(POJOObject pObj){
           }

Is it possible to pass more than one Pojo object
as below
 @POST
            @Path("/test")
            @Produces(MediaType.APPLICATION_JSON)
            public Response addSomething(POJOObject pObj,POJOObject2 pObj1){
               }

This can be achieved by creating an aggregate object containing both the objects (pObj and pObj1)
But was wondering if there is any other solution to achieve this.


text:
Q: std::condition_variable::notify_one() does not wake up a waiting thread I have a code something like the following:
#include <mutex>
#include <condition_variable>
#include <future>

std::mutex mtx;
std::condition_variable cv;
std::future<void> worker;

void worker_thread() {
  {
    std::lock_guard<std::mutex> lg{ mtx };
    // do something 1
  }
  cv.notify_one();

  // do something 2
}

int main() {
  {
    std::unique_lock<std::mutex> lg{ mtx };
    worker = std::async(std::launch::async, worker_thread);
    cv.wait(lg);
  }
  // do something 3
}

The main thread does not proceed to // do something 3 and I can't understand why. I thought the line cv.notify_one() should be reached from the worker thread after cv.wait(lg) has been passed by the main thread, so there is no reason to hang.
The worker thread is responsible for some streaming data processing, while the main thread is mainly responsible for GUI event processing.
// do something 1 is about some initialization that should be done inside the worker thread. The main thread should wait for the worker thread to finish it.
// do something 2 is the main job of the worker thread.
// do something 3 is the main job of the main thread.
Changing cv.notify_one() to cv.notify_all() didn't help.
Is this usage of condition variable correct?

A: I have to backtrack on my original answer, and I apologize to Junekey for that. I misread the code, and concluded there was a race condition. I cannot reproduce the problem. We need an example that actually blocks forever on the cv.wait in order to figure out why it is doing so. Nevertheless, the code is incorrect if for no other reason than that it could get a spurious notification and pass through cv.wait before the worker_thread calls cv.notify. That rarely happens, but it does happen.
This code is more or less canonical:
#include <mutex>
#include <condition_variable>
#include <thread>

std::mutex mtx;
std::condition_variable cv;
bool worker_done = false;  // <<< puts the "condition" in condition_variable

void worker_thread() {

    // do something 1

    {
        std::lock_guard<std::mutex> lg{ mtx };
        worker_done = true;  // ... and whatever
    }

    cv.notify_one();

    // do something 2
}

int main() {
    std::thread workman(worker_thread);
    {
        std::unique_lock<std::mutex> lg{ mtx };
        while (!worker_done) {
            cv.wait(lg);
        }
    }
    // do something 3
    workman.join();
}

A: I'm sorry. The question was totally wrong.
I think the claim "notification should be fired after the main thread have begun to wait" is still right, but the root cause of the hang was spurious awakening, as Jive Dadson and Erik Alapää pointed out.
There was a reason I couldn't compile the code w/o optimization options, so I misinterpreted the point of hang because the point where the debugger was pointing to was not very clear. The point of hang was not the line cv.wait(lg). It was somewhere inside // do something 3.
I have a flag that is set if // do something 1 has been succeeded, while it is cleared if an exception is thrown inside // do something 1. In // do something 3, the flag is checked and if it indicates failure, the main thread calls worker.get() to rethrow the exception. Since // do something 2 is a form of infinite loop, the main thread just hangs if cv has waken up spuriously so that the flag is not yet set.
Now it works fine! Thanks everyone.


text:
Q: Como salvar as credenciais do Git no Linux? No meu Ubuntu, quando dou um pull, push e etc. O git sempre pede meu usuário e senha. Como faço para isso ficar salvo?

A: Armazenando Permanentemente
Se quiser fazer no terminal, execute o comando abaixo.
git config credential.helper store
git push origin main

Informe seu usuário e/ou sua senha e aperte ENTER. Após isso, sua senha ficará salva permanentemente.
Armazenando Temporariamente
Se quiser fazer no terminal, execute o comando abaixo.
git config credential.helper cache
git push origin main

Informe seu usuário e/ou sua senha e aperte ENTER. Após isso, sua senha ficará salva por 900 segundos. Caso queira aumentar ou diminuir o tempo, utilize a flag --timeout:
git config credential.helper 'cache --timeout <seconds>'

Observação: Você pode usar a flag --global após git para aplicar a alteração em todos os repositórios locais

No Windows
No Windows, você pode usar o Git Credential Manager Core para gerenciar suas credenciais


text:
Q: Can I Define an Filteredtextboxextender FilterType(s) using the web.config file So I have a scenario where I need to change the filter type of an Filteredtextboxextender based on a value in the config file in my asp.net project.
This change propagates through about 80 input forms currently.
Since my web.config value is a string I need to do an if statement on every page to define the filter type.
e.g.
If ConfigurationManager.AppSettings("SomeVariable") = "A" Then
     txtLTWo_Filteredtextboxextender.FilterType = AjaxControlToolkit.FilterTypes.LowercaseLetters Or AjaxControlToolkit.FilterTypes.UppercaseLetters Or AjaxControlToolkit.FilterTypes.Numbers
ElseIf ConfigurationManager.AppSettings("SomeVariable") = "B" Then
     txtLTWo_Filteredtextboxextender.FilterType = AjaxControlToolkit.FilterTypes.Numbers
Else
     txtLTWo_Filteredtextboxextender.FilterType = AjaxControlToolkit.FilterTypes.Custom
     txtLTWo_Filteredtextboxextender.ValidChars = "!QW"
End If

The problem here is that a change to a filter type for a particular result would have me changing every page.
I would really like a way to define it in the config file directly.
Something like this, but obviously doesn't work.
txtML_Wo_Filteredtextboxextender.FilterType = ConfigurationManager.AppSettings("FilterType")

The only way to do it that I can come up with is to keep the filter as AjaxControlToolkit.FilterTypes.Custom
And then define the string of valid characters in the config file. However this would be a large string and seems senseless when the filter has the attributes I need.
Any ideas to streamline this would be great, thanks in advance.

A: Hum some ideas to float here:
On page pre render (not 100% sure of the event), the you can/could inject that code.
Or you simple have a global function in a code module that fetches the config settings you have, and then use this:
this:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <ajaxToolkit:FilteredTextBoxExtender ID="TextBox1_FilteredTextBoxExtender"
            runat="server" BehaviorID="TextBox1_FilteredTextBoxExtender"
            TargetControlID="TextBox1"
            FilterType="LowercaseLetters" >
        </ajaxToolkit:FilteredTextBoxExtender>

becomes:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <ajaxToolkit:FilteredTextBoxExtender ID="TextBox1_FilteredTextBoxExtender"
            runat="server" BehaviorID="TextBox1_FilteredTextBoxExtender"
            TargetControlID="TextBox1"
            FilterType="<%= MyFilterType() %>" >
        </ajaxToolkit:FilteredTextBoxExtender>

Or say Module1.FilterType().
So, we could say have a global vb function, and then use a sever side expression in the markup settings.
I don't know what (if) those values like Filter Type "LowercaseLetters" are string or enum???
However, a server side expression in the markup could and should work.
Public Function MyFilterType() as string ???

   code here to fetch the setting from config

   return strSetting
End Function


text:
Q: logname: no login name I am trying to understand the differences between logname and LOGNAME from Difference between logname and $LOGNAME and https://askubuntu.com/questions/490620/difference-between-logname-and-logname
On Lubuntu 18.04, why did I get logname: no login name?
t@ocean:/t/t/bkg$ echo $LOGNAME
t
t@ocean:/t/t/bkg$ logname
logname: no login name
t@ocean:/t/t/bkg$ su t
Password:
t@ocean:/t/t/bkg$ logname
logname: no login name
$ echo $?
1
t@ocean:/t/t/bkg$ cat /var/run/utmp
~~~reboot4.15.0-22-generic��[8Jtty1tty1LOGINJ��[�!�tty7:0t:0��[��5~~~runlevel4.15.0-22-generic��[

t@ocean:/t/t/bkg$ sudo su
[sudo] password for t:
root@ocean:/tmp/test/bkg# logname
logname: no login name
root@ocean:/tmp/test/bkg# echo $LOGNAME
root

What is logname supposed to output?
Thanks.
From man logname:

logname - print user´s login name
Print the name of the current user.

To address the comments:
$ cat /proc/self/loginuid
4294967295

t@ocean:/t/t/bkg$ grep ":$(id -u):" /etc/passwd
t:x:1000:1000:t,,,:/home/t:/bin/bash

t@ocean:/t/t/bkg$ tty
/dev/pts/8
t@ocean:/t/t/bkg$ w
 17:52:08 up 5 days,  6:28,  1 user,  load average: 0.39, 0.29, 0.28
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
t        tty7     :0               Wed11    5days  1:47m  6.33s /usr/bin/lxsession -s Lubuntu -e LXDE

Mark suspected the cause is that my lxterminal doesn't  add an entry to utmp.
Pandya: Oh. Seems a bug with entry as you've concluded.


text:
Q: Usage of strtok() I tried my insertItem() list api inserting all types of items, successfully, for example, strings(below),
static void copyData(List *records, char *delim, char *argv[]){

char *item = malloc(5);
    strcpy(item, "abcd");
    int count = 0;
    while(count++ < 10){

      insertItem(records, item);

      item = malloc(5);
      strcpy(item, "efgh");
    }
}

Output:
$ ./frequencyCounter.exe ARRAY
Key is:abcd
Key is:efgh
Key is:efgh
Key is:efgh
Key is:efgh
Key is:efgh
Key is:efgh
Key is:efgh
Key is:efgh
Key is:efgh
Size of list: 10
Before freeList()After freeList()

But strtok() tokens shows problem code, as shown below, buf[] parameter not required above,
static void copyData(List *records, char buf[], char *delim, char *argv[]){

  char *token =  strtok(buf, delim);

  void *item = malloc(strlen(token) + 1);
  item = memcpy(item, token, strlen(token)+1);
    printf("token-%s\n", token);
  while(token != NULL){

    insertItem(records, item);
    token = strtok(NULL, delim);
    if(token != NULL){
      printf("token-%s\n", token);
      item = malloc(strlen(token) + 1); //every item has its own heap memory
      memcpy(item, token, strlen(token)+1);
    }
  }

}

Output is,
$ ./frequencyCounter.exe ARRAY
token-it
token-was
token-the
token-best
token-of
token-times
Key is:it
Key is:it
Key is:it
Key is:it
Key is:it
Key is:it
Size of list: 6
Aborted (core dumped)

In the problem code(above), Can we re-use the result of strtok()?

A: Although it's quite hard to understand or read your code, the following looks bad
item = malloc(strlen(token));

you then memcpy() strlen(token) + 1 bytes.
This will cause undefined behavior and thus your program will behave erratically.
Also, don't overuse strlen() it iterates through all the characters of the input string every time you call it, instead just store the result somewhere if you will need to use it more than once.
This is an improved version of your function
static void
copyData(List *records, char buf[], char *delim, char *argv[])
{
    char *token;
    size_t length;
    void *item;

    token = strtok(buf, delim);
    if (token == NULL)
        return;
    length = strlen(token);
    item = malloc(length + 1);
    if (item == NULL)
        return;
    memcpy(item, token, length + 1);

    printf("token-%s\n", token);
    while (token != NULL) {
        insertItem(records, item);

        token = strtok(NULL, delim);
        if (token != NULL) {
            length = strlen(token);

            item = malloc(length + 1); // every item has its own heap memory
            if (item != NULL) {
                memcpy(item, token, length + 1);
            }
            printf("token-%s\n", token);
        }
    }
    // Some day, you will have to free these pointers
}

But I hope it's not just like this, because every item you malloc() will never be freed and also, because it violates the DRY principle somewhat. And one more thing, you can use strdup() too.


text:
Q: Node js runtime profiling measurement I am new to node.js but I surprised by searching and finding no way to measure run time profile of a function in node.js via code (not looking for an external tool). I am looking for something like this
// store time
run_function1();
// store time
// calculate time difference
console.log('function1 ran in '+time_diff+' seconds');

A: Take a look at performance.now()
As example says:
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");

A: Try the node.js built in profiler.

A: There is also a function in Node.js that is called hrtime to get high resolution timings.
Node Doc
const NS_PER_SEC = 1e9;
const time = process.hrtime();
// [ 1800216, 25 ]

setTimeout(() => {
  const diff = process.hrtime(time);
  // [ 1, 552 ]

  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
  // benchmark took 1000000552 nanoseconds
}, 1000);


text:
Q: How this expression is going to sort the results sorted(list1 ,key = lambda x:-x[0]) data = sorted(zip(list1,list2),key = lambda x:-x[0])

how this expression is going to sort the results . if we have used x[0] and x[-1] the results would be forward and backward but here we are using -x[0].


text:
Q: jQuery intro to syntax and having a syntax error Hello I am just starting the CodeCademy program on jQuery. One of the very first assignments is just asking me to 'call' on a function called ".ready". I am apparently having some sort of syntax error as I keep getting the response "Oops, try again. Did you put document inside $() ?" I know its insanely simple but I have zero jQuery knowledge and am really stuck here. Thanks guys
$(document).ready(function(){

});
$(document).ready();

A: You are calling the function ready() twice.
The first time, you are also calling a handler, which is going to execute once the DOM is ready.
You can also see how the ready() function works here.

A: There does not appear to any "syntax error" at js at Question. The response

"Oops, try again. Did you put document inside $() ?"

seems to be a notification message generated by the program submitting js in.

jQuery.fn.ready() simply returns this ; if function passed as parameter , calls function passed . See also jQuery.ready , jQuery.isReady , jQuery.readyWait
function (fn) {
    // Add the callback
    jQuery.ready.promise().done(fn);

    return this;
}

window.onerror = function(e) {
  console.log(e)
}

$(document).ready(function() {

});

console.log($(document).ready()
            , $("body").ready()
            , $("body").ready().find("span").text()
           );

$(document).ready(function() {
  alert($("span").text())
});

$("body").ready(function() {
  alert($("span").text())
});

abc

jsfiddle http://jsfiddle.net/sgmhv3a8/


text:
Q: TFS: Exception calling "SetRight" with "2" argument(s): "Could not obtain the user information." I have a release definition in TFS with 2 tasks. One of them passes perfectly, while the other throws an exception, though both have very smimlar configuration.
The successful task configuration:
CopyFile Task
Source: $(System.DefaultWorkingDirectory)/XXX Build Definition/drop
Machines $(WebServers)
Admin Login: server\user
Password: Password
Protocol: HTTP
Destination Folder: C:\DestFolder

Variables: WebServers: MyServer

The failing task configuration:
RunPowerShellOnRemoteComputer Task
Machines $(WebServers)
Admin Login: server\user
Password: Password
Protocol: HTTP

PowerShell Script: C:\...\script.ps1

Variables: WebServers: MyServer

When running the second task I receive this exception:

Exception calling "SetRight" with "2" argument(s): "Could not obtain
  the user information."   CategoryInfo :NotSpecified: (:) [],
  MethodInvocationException   FullyQualifiedErrorId :Exception   --->
  System.Management.Automation.RemoteException: Exception calling
  "SetRight" with "2" argument(s): "Could not obtain the user
  information."
      --- End of inner exception stack trace ---
      at Microsoft.VisualStudio.Services.DevTestLabs.Deployment.Deployment.PowershellExecutor.Invoke(String
  errorContextMessage, Boolean writeResultToLog, Boolean isCancellable)
      at Microsoft.VisualStudio.Services.DevTestLabs.Deployment.Deployment.RemoteDeploymentHelper.InstallServiceInternal(String
  serviceSourcePath, String serviceName, String destinationFileName)
      at Microsoft.VisualStudio.Services.DevTestLabs.Deployment.Deployment.RemoteDeploymentHelper.InstallService(String
  serviceSourcePath, String serviceName, String destinationFileName)
      at Microsoft.VisualStudio.Services.DevTestLabs.Deployment.Deployment.DeploymentClient.d__24.MoveNext()
  ---> (Inner Exception #0) System.Management.Automation.RemoteException: Exception calling
  "SetRight" with "2" argument(s): "Could not obtain the user
  information."<---
       Deployment status for machine 'bgsovswops.eu.hpecorp.net:5985' : 'Failed'  ##[error], MethodInvocationException\r\n
  FullyQualifiedErrorId :Exception\r\n"}};]
       ##[error]System.Management.Automation.RuntimeException: Failed to install
  'VisualStudioRemoteDeployer3e199746-ae71-4ba0-a2ef-f5ce8f25a631' from
  service executable path VisualStudioRemoteDeployer.exe . Consult the
  logs below:  Exception calling "SetRight" with "2" argument(s): "Could
  not obtain the user information."   CategoryInfo :NotSpecified: (:)
  [], MethodInvocationException   FullyQualifiedErrorId :Exception
  ---> System.Management.Automation.RuntimeException: Failed to install 'VisualStudioRemoteDeployer3e199746-ae71-4ba0-a2ef-f5ce8f25a631' from
  service executable path VisualStudioRemoteDeployer.exe . Consult the
  logs below:  Exception calling "SetRight" with "2" argument(s): "Could
  not obtain the user information."   CategoryInfo :NotSpecified: (:)
  [], MethodInvocationException   FullyQualifiedErrorId :Exception
--- End of inner exception stack trace ---
at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable

input)
      at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspace
  rs, Boolean performSyncInvoke)
      at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace
  rsToUse, Boolean isSync)
      at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection1
  input, PSDataCollection1 output, PSInvocationSettings settings)
      at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection1
  input, PSDataCollection1 output, PSInvocationSettings settings)
      at Microsoft.TeamFoundation.DistributedTask.Handlers.LegacyVSTSPowerShellHost.VSTSPowerShellHost.Main(String[]
  args)

When I go to the remote machine, I succesfully execute the 'Invoke-Expression' on the C:...\script.ps1.
Also, I successfully connect from the local machines' powerscript console to the remote machine.
Any suggestions appreciated.

A: Please include the domain in the username variable. If it's not domain environment, it should be the machine name.
So, just try to update the UPN user name format to DOMAIN\Username or MACHINENAME\Username format.

A: Check NetLogon Windows Service
The target server that I was deploying to reported this error. I already had the username for the PowerShell on Target Machines task set to use full DOMAIN\Username, per Andy's answer.
It turned out that the machine's NetLogon service had not started properly when the machine booted, due to it running on an abnormally busy VSphere cluster.
A reboot of the machine ensured that the NetLogon Windows Service, and its dependent services were all started, following which a redeploy succeeded.


text:
Q: Storing json array in SQL table I have two tables: user and phone. The table phone has a reference to the table user. This allows several phone numbers for each user.
I am sending the information to the SQL server in json format, but I am struggeling to store the phone numbers. This is what I have so far:
CREATE TABLE [dbo].[user](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

CREATE TABLE [dbo].[phone](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [userId] [int] NOT NULL,
    [type] [varchar](12) NOT NULL,
    [phone] [varchar](12) NOT NULL
) ON [PRIMARY]
GO

DECLARE @jsonVariable NVARCHAR(MAX)

SET @jsonVariable = N'{
   "name":"Joe Smith",
   "phones":[
      {
         "phone":"+1 123 123-4567",
         "type":"business"
      },
      {
         "phone":"+1 987 987-6543",
         "type":"mobile"
      }
   ]
}'

DECLARE @userId int
DECLARE @userName varchar(max) = (SELECT userName FROM OPENJSON (@jsonVariable) WITH (userName varchar(max) N'$.name'))
INSERT INTO [dbo].[user] ([name]) VALUES (@userName)

SET @userId = @@IDENTITY

The question now is: is there something like a "forEach" routine to store all phone numbers?

A: You can use OPENJSON to get all the records from the phones array in your json.
Try this as part of your existing code:
INSERT INTO [dbo].[phone] (
                              [userId]
                            , [type]
                            , [phone]
                          )
            SELECT @userId
                 , [c].[type]
                 , [c].[phone]
            FROM   [dbo].[user] [a]
            INNER JOIN OPENJSON(@jsonVariable)
                       WITH (
                                [userName] VARCHAR(MAX) '$.name'
                              , [phones] NVARCHAR(MAX) AS JSON --bring your phones array back out.
                            ) AS [b]
                ON [b].[userName] = [a].[name]
            CROSS APPLY OPENJSON([b].[phones]) --Cross apply to get all records. This will return all the records in phones for the specific user you have inserted in dbo.[user]
                       WITH (
                                [phone] NVARCHAR(12) '$.phone'
                              , [type] NVARCHAR(12) '$.type'
                            ) [c];


text:
Q: DateDiff between years resulting wrong result I got this function from the internet. It's doing well when counting days so far, but when the dates is from different year, the result is wrong.
Example:
dateFrom = "2017-12-26"
dateTo = "2018-01-02"

the result will be 28 days, when it supposed to be 6 days.
Here is the function:
Public Function NetWorkdays(dtStartDate, dtEndDate, arrHolidays)
    Dim lngDays
    Dim lngSaturdays
    Dim lngSundays
    Dim lngHolidays
    Dim lngAdjustment
    Dim dtTest
    Dim i, x

    lngDays = DateDiff("d", dtStartDate, dtEndDate)
    lngSundays = DateDiff("ww", dtStartDate, dtEndDate, vbSunday)
    lngSaturdays = DateDiff("w", IIf(Weekday(dtStartDate, vbSunday) = vbSaturday, dtStartDate, dtStartDate - Weekday(dtStartDate, vbSunday)), dtEndDate)

    For x = LBound(arrHolidays) To UBound(arrHolidays)
        For i = 0 To lngDays
            dtTest = DateAdd("d", i, dtStartDate)
            If arrHolidays(x) = dtTest And Weekday(dtTest) <> 1 And Weekday(dtTest) <> 7 Then
                lngHolidays = lngHolidays + 1
            End If
        Next
    Next

    If Weekday(dtStartDate, vbSunday) = vbSunday Or Weekday(dtStartDate, vbSunday) = vbSaturday Then
        lngAdjustment = 0
    Else
        lngAdjustment = 1
    End If

    NetWorkdays = lngDays - lngSundays - lngSaturdays - lngHolidays + lngAdjustment
End Function

Public Function IIf(expr, truepart, falsepart)
    If expr Then IIf = truepart Else IIf = falsepart
End function

Can anybody point it out anything to repair?

A: dateFrom = #2017-12-26#
dateTo = #2018-01-02#
Msgbox Dateto - datefrom,, "Result"

returns
---------------------------
Result
---------------------------
7
---------------------------
OK
---------------------------

A: As indiated by the type prefixes in the prototype:
Public Function NetWorkdays(dtStartDate, dtEndDate, arrHolidays)

the function expects Dates, not Strings. Evidence:
Option Explicit

(copy of function)

Dim dp, n
For Each dp In Array(Array("2017-12-26", "2018-01-02"))
   On Error Resume Next
    n = NetWorkdays(dp(0), dp(1), Array())
    If Err Then n = Err.Description
   On Error GoTo 0
    WScript.Echo TypeName(dp(0)), dp(0), dp(1), n
    dp(0) = CDate(dp(0))
    dp(1) = CDate(dp(1))
    WScript.Echo TypeName(dp(0)), dp(0), dp(1), NetWorkdays(dp(0), dp(1), Array())

Next

output (german locale):
cscript 47921079.vbs
String 2017-12-26 2018-01-02 Typenkonflikt
Date 26.12.2017 02.01.2018 6

Depending on versions, locales and the phase of the moon, you may have to replace the CDate() call with something more reliable.


text:
Q: Network bound transformation and threading I am trying to use a REST API to enrich data I have in a spark dataframe.  The REST API isn't built by me and requires a single input at a time (no batch option).  Unfortunately the REST API latency is slower than I would like so my spark applications seem to spend a lot of time waiting for the API to iterate over each row.  Although my REST API has higher latency, it does have very high throughput/capacity which does not seem to get fully used by my spark application.
Since my application appears to be network bound, I was wondering if it would make sense to use threading to help improve the speed of my application.  Does spark already capable of doing this internally?  If using threads does make sense, is there an easy way to accomplish this?  Has anybody successfully done this?

A: I've encountered the same problem when fetching data from a blob storage.
Below is a small self-contained dummy example that I think you can easily modify for your needs.
In the example you should be able to register that it takes a lot longer to construct df_slow vs constructing df_fast.
It works by making each worker process a list of rows in parallel, instead of processing one row at a time sequentially.
You might be able to just swap the slowAdd function with your own Row transforming function. The slowAdd function simulates network latency by sleeping 0.1 seconds.
import pyspark.sql.functions as F
import pyspark.sql.types as T
from pyspark.sql import Row
# Just some dataframe with numbers
data = [(i,) for i in range(0, 1000)]
df = spark.createDataFrame(data, ["Data"], T.IntegerType())

# Get an rdd that contains 'list of Rows' instead of 'Row'
standardRdd =  df.rdd # contains [row1, row3, row3,...]
number_of_partitions = 10
repartionedRdd = standardRdd.repartition(number_of_partitions) # contains [row1, row2, row3,...] but repartioned to increase parallelism
glomRdd = repartionedRdd.glom() # contains roughly [[row1, row2, row3,..., row100], [row101, row102, row103, ...], ...]
                                # where the number of sublists corresponds to the number of partitions

# Define a transformation function with an artificial delay.
# Substitute this with your own transformation function.
import time
def slowAdd(r):
  d = r.asDict()
  d["Data"] = d["Data"] + 100
  time.sleep(0.1)
  return Row(**d)

# Define a function that maps the slowAdd function from 'list of Rows' to 'list of Rows' in parallel
import concurrent.futures
def slowAdd_with_thread_pool(list_of_rows):
  thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=100)
  return [result for result in thread_pool.map(slowAdd, list_of_rows)]

# Perform a fast mapping from 'list of Rows' to 'Rows'.
transformed_fast_rdd = glomRdd.flatMap(slowAdd_with_thread_pool)

# For reference, perform a slow mapping from 'Rows' to 'Rows'
transformed_slow_rdd = repartionedRdd.map(slowAdd)

# Convert the rdds back to dataframes from the rdd's
df_fast = spark.createDataFrame(transformed_fast_rdd)
#This sum operation will be fast (~100 threads sleeping in parallel on each worker)
df_fast.agg(F.sum(F.col("Data"))).show()

df_slow = spark.createDataFrame(transformed_slow_rdd)
#This sum operation will be slow (1 thread sleeping in parallel on each worker)
df_slow.agg(F.sum(F.col("Data"))).show()


text:
Q: HTML Table not working in Mail I am creating a runtime HTML table and sending via mail. The table is added in the body of mail. But when the mail is triggered it is showing System.Web.UI.HtmlControls.HtmlTable instead of the contents of the table.
// .csPage:
HtmlTable tbl = new HtmlTable();
        tbl.Border = 1;
        tbl.CellSpacing = 0;
        HtmlTableRow trHeader = new HtmlTableRow();
        HtmlTableCell tcHeader = new HtmlTableCell();
        tcHeader.InnerText = "Mobile Number";
        HtmlTableCell tc1Header = new HtmlTableCell();
        tc1Header.InnerText = "Carrier";
        trHeader.Cells.Add(tcHeader);
        trHeader.Cells.Add(tc1Header);
        tbl.Rows.Add(trHeader);
 for (int i = 0; i < dvNumbers.Rows.Count; i++)
            {
                HtmlTableRow tr = new HtmlTableRow();
                HtmlTableCell tc = new HtmlTableCell();
                tc.InnerText = dvNumbers.Rows[i].Cells[0].Text;
                tr.Cells.Add(tc);
                HtmlTableCell tc1 = new HtmlTableCell();
                tc1.InnerText = dvNumbers.Rows[i].Cells[1].Text;
                tr.Cells.Add(tc1);
                tbl.Rows.Add(tr);

            }

            objMail.MobileDeactivationMail(txtMailTo.Text, txtMailCC.Text, txtMailBCC.Text, tbl);

// Mail Code:
public bool MobileDeactivationMail(string strReceiverMailId, string CC, string BCC, HtmlTable tbl)
    {
        bool blnIsMailSent = false;
        MailMessage objMailMsg;
        try
        {
            objMailMsg = new MailMessage();
            MailAddress FromAdd = new MailAddress("x@x.com");
            objMailMsg.From = FromAdd;
            objMailMsg.To.Add(new MailAddress(strReceiverMailId));
            if (CC != "")
                objMailMsg.CC.Add(new MailAddress(CC));
            if (BCC != "")
                objMailMsg.Bcc.Add(new MailAddress(BCC));
            objMailMsg.Subject = "Deactivation of Mobile Numbers";
            objMailMsg.Priority = MailPriority.High;
            objMailMsg.IsBodyHtml = true;
            objMailMsg.Body = "

 Dear Sir/Mam</td<
," + "

	         Kindly Deactivate the following mobile numbers.

" + tbl + "

Regards,

HR

";
            SmtpClient SmtpMail = new SmtpClient();
            SmtpMail.Port = 25;
            SmtpMail.Host = "xxxxx";
            System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("xxxxxxx", "xxxxx");
            SmtpMail.UseDefaultCredentials = false;
            SmtpMail.Credentials = SMTPUserInfo;
            SmtpMail.Send(objMailMsg);
            objMailMsg.Dispose();
            blnIsMailSent = true;
        }
        catch (Exception Ex)
        {
            blnIsMailSent = false;
        }

        return blnIsMailSent;
    }

Where i am going wrong?

A: Your problem is with this line:
objMailMsg.Body = "

 Dear Sir/Mam</td<
," + "

	Kindly Deactivate the following mobile numbers.

" + tbl + "

Regards,

HR

";

Specificially:
" + tbl + "

As you are concatenating the object into your string, it will call tbl.ToString()
By default, this will return the class name - not the HTML of the table as you desire.
The way to solve this, using HTML table, is to write out the HTML directly. Unfortunately, InnerText and InnerHTML, although present, are not supported on this control (MSDN HTMLTable Properties), so instead you have to use the RenderControl (MSDN RenderControl documentation) method:
        StringWriter writer = new StringWriter();
        Html32TextWriter htmlWriter = new Html32TextWriter(writer);
        tbl.RenderControl(htmlWriter);
        string html = writer.ToString();

You can then concatenate this HTML string instead of tbl.


text:
Q: What is the Laurent series for the given function? How do we find a Laurent series for
the function $$f(z)=\frac{z+1}{z-1}$$ in the region $1<|z|<\infty$? I can find for the region $|z| < \infty$ easily and in terms of powers of $z$. But the question I think is to find in powers of $z-1$.

A: Hints:
$$|z|>1\implies\frac1{|z|}<1\implies \frac{z+1}{z-1}=\frac{z+1}z\frac1{1-\frac1z}=$$
$$=\frac{z+1}z\sum_{k=0}^\infty\frac1{z^k}=\ldots$$


text:
Q: How to limit the number of displayed kivy spinner items I am am currently using the spinner widget of kivy and i would like to know if there is a way to limit the number of items the spinner shows and scroll to see the rest.
For example, i am using a spinner to display all the months, so when i click the spinner, the list reaches the bottom of the window. I would like to see maybe like 5-6 options and scroll to see the rest of them.

A: You can use the dropdown_cls.max_size property to specify the maximum height of the drop-down list:
from kivy.base import runTouchApp
from kivy.uix.spinner import Spinner

max = 10
spinner = Spinner(
    text='Values',
    values=(str(n) for n in range(1, 20)),
    size_hint=(None, None),
    size=(100, 44),
    pos_hint={'center_x': .5, 'center_y': 0.9})

spinner.dropdown_cls.max_height = spinner.height* max + max * 4

runTouchApp(spinner)


text:
Q: How to get contacts address from Contacts.SearchAsync results? I am binding a listbox with contacts address using following xaml code
<ListBox Name="ContactResultsDataLINQ" ItemsSource="{Binding}" Height="200" Margin="24,0,0,0" DataContext="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Path=Addresses[0].PhysicalAddress.AddressLine1, Mode=OneWay}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

However, this only binds AddressLine1...what i want it complete address = AddressLine1 + AddressLine2 + City
Now how do i append this additional properties via xaml code ?

A: Either use two TextBlock elements, or combine it in a single, using Run elements.
<TextBlock>
    <Run Text="{Binding Path=Addresses[0].PhysicalAddress.AddressLine1, Mode=OneWay}" />
    <Run Text=" " />
    <Run Text="{Binding Path=Addresses[0].PhysicalAddress.AddressLine2, Mode=OneWay}" />
    <Run Text=" " />
    <Run Text="{Binding Path=Addresses[0].PhysicalAddress.City, Mode=OneWay}" />
</TextBlock>


text:
Q: Flutter keep client alive doesn't wrok I have an app that switches widgets on a page.
(custom made container with 2 gestureDetectors to switch between the 2 pages)
the stateless widget to switch the pages: (it returns the chosen widget)
  class Layer2 extends StatelessWidget {
  Layer2({this.pageName});

  PageSelect pageName;
  @override
  Widget build(BuildContext context) {
    if (pageName == PageSelect.Friends) {
      return DiscoverFriends();
    } else if (pageName == PageSelect.FriendRequests) {
      return Requests();
    } else {
      return Text("");
    }
  }
}

Then I use this stful widget where I added the 'keep alive client'.
class Requests extends StatefulWidget {
  @override
  _RequestsState createState() => _RequestsState();
}

class _RequestsState extends State<Requests>
    with AutomaticKeepAliveClientMixin<Requests> {

  @override
  bool get wantKeepAlive => true;

etc....
It works, but it doesn't keep the 2 widgets alive. (when I switch, the init state runs again)
What am I doing wrong?
Thanks in advance!

A: Firstly you should understand the lifecycle of Flutter. If you call the widget with navigator you get a new one, so if you want to call the same, I mean the previous one, you should use 'Navigator.pop' function.


text:
Q: java file input with rewind()/reset() capability I need to write a function that takes in some kind of input stream thing (e.g. an InputStream or a FileChannel) in order to read a large file in two passes: once to precompute some capacities, and second to do the "real" work. I do not want the whole file loaded into memory at once (unless it is small).
Is there an appropriate Java class that provides this capability? FileInputStream itself does not support mark()/reset(). BufferedInputStream does, I think, but I'm not clear whether it has to store the whole file to do this.
C is so simple, you just use fseek(), ftell(), and rewind(). :-(

A: java.nio.channels.FileChannel has a method position(long) to reset the position back to zero like fseek() in C.

A: RandomAccessFile is what you want:

*

*fseek() is translated to RandomAccessFile#seek

*ftell() is translated to RandomAccessFile#getFilePointer

*rewind() is seek(0)

A: I think the answers referencing a FileChannel are on the mark .
Here's a sample implementation of an input stream that encapsulates this functionality. It uses delegation, so it's not a true FileInputStream, but it is an InputStream, which is usually sufficient. One could similarly extend FileInputStream if that's a requirement.
Not tested, use at your own risk :)
public class MarkableFileInputStream extends FilterInputStream {
    private FileChannel myFileChannel;
    private long mark = -1;

    public MarkableFileInputStream(FileInputStream fis) {
        super(fis);
        myFileChannel = fis.getChannel();
    }

    @Override
    public boolean markSupported() {
        return true;
    }

    @Override
    public synchronized void mark(int readlimit) {
        try {
            mark = myFileChannel.position();
        } catch (IOException ex) {
            mark = -1;
        }
    }

    @Override
    public synchronized void reset() throws IOException {
        if (mark == -1) {
            throw new IOException("not marked");
        }
        myFileChannel.position(mark);
    }
}

A: BufferedInputStream supports mark by buffering the content in memory. It is best reserved for relatively small look-aheads of a predictable size.
Instead, RandomAccessFile can be used directly, or it could serve as the basis for a concrete InputStream, extended with a rewind() method.
Alternatively, a new FileInputStream can be opened for each pass.

A: If you get the associated FileChannel from the FileInputStream, you can use the position method to set the file pointer to anywhere in the file.
FileInputStream fis = new FileInputStream("/etc/hosts");
FileChannel     fc = fis.getChannel();

fc.position(100);// set the file pointer to byte position 100;

A: Check out java.io.RandomAccessFile

A: PushbackInputStream will also work, as long as you know how many characters you want to be able to rewind

A: BufferedInputStream has mark(readlimit) and reset().
readlimit should be larger than filesize to make mark valid.
file.length()+1 is OK.
This means mark is valid until readlimit bytes are read, thus you can go back by reset().

A: What you want is RandomAccessFileInputStream - implements InputStream interface with mark/reset, sometimes seek based on RandomAccessFiles. Some implementations exist which might do what you need.
One example complete with sources is in http://www.fuin.org/utils4j/index.html but you would find many others searching the internet and its is easy enough to code if none fits exactly.


text:
Q: Install Apps from the AppStore the automatic way I'm trying to write a script which makes it possible to download Apps from Apples AppStore the automatic way (on an jailbreaked device). So I can tell the script the names (or IDs) of the Apps (via JSON e.g.) and the script begins to download and install by its self.
Has anybody an idea how to implement such stuff?


text:
Q: Keeping the first N elements of a std::vector<> and removing the rest I have a std::vector<int> variable in my C++ application. The size of the vector is determined at runtime, but is typically about 1000.
I have sorted this vector (which works well), and after sorting, I would like to keep only the first 50 elements.
I have tried:
kpts.erase(kpts.begin() + 50, kpts.end());

where kpts is my vector, and the performance is horrible! Presumably because of the way erase operates.
Is there a way to only keep the first 50 elements of a vector? It seems like it should be obvious, but I can't find a way to do this.

A: Yes, you can use std::vector::resize, which just truncates if the length of the vector is greater than n.
See here: http://www.cplusplus.com/reference/vector/vector/resize/
std::vector<int> myvector;

for (int i=1;i<1000;i++) myvector.push_back(i);

myvector.resize(50);
// myvector will contain values 1..50


text:
Q: excluded field in model form still required I have the following form:
class PostForm(forms.ModelForm):
    post_type = forms.ChoiceField(widget=forms.RadioSelect(attrs={'name': 'radioInline'}), choices=POST_CHOICES)

    class Meta:
        model = Post
        fields = ('title','desc','image','url',)

I have the following model:
@python_2_unicode_compatible
class Post(models.Model):
    entity = models.ForeignKey('companies.Entity')
    title = models.CharField('Post Title', max_length=128, unique=True)
    desc = models.TextField('Description', blank=True, null=True)
    post_type = models.IntegerField(choices=POST_CHOICES)
    image = models.ImageField('Post Image', upload_to='post', blank=True, null=True)
    url = models.URLField(max_length=255, blank=True, null=True)
    slug = models.SlugField(blank=True, null=True, unique=True)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

When I submit the form, I get the error:
post_type field error: This field is required.
I want to populate this field after form.is_valid method.
Since this field is not in the required fields tuple, shouldn't it not be required?
I have also tried adding:
post_type = models.IntegerField(choices=POST_CHOICES, blank=True)

Though I get the same error.
Is there something else going on?

A: post_type = forms.ChoiceField(widget=forms.RadioSelect(attrs={'name': 'radioInline'}), choices=POST_CHOICES, required=False)

add required=False will fine

your post_type = models.IntegerField(choices=POST_CHOICES, blank=True) in models.py not work because you have override post_type field in ModelForm and not set it to required=False

if you want post_type = models.IntegerField(choices=POST_CHOICES, blank=True) work just:
class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('title','desc','image','url', 'post_type')


text:
Q: Automate Function / Create a Hook for Cron Job Task (WordPress) I am using a Plugin in Wordpress which has a Button integrated. I want to schedule the function of the button into a Cron Job, which will execute the function of the button automatically so i dont have to click that button.
For that, im trying to use another Plugin (WP Cron Jobs or something). Through this Plugin, im able to add a new task via Hook or PHP. But I cant find the right snippet of code to enter.
The code I have of the function i want to automate:
    namespace SabaiApps\Directories\Component\System\Tool;

    class RunCronTool extends AbstractTool
    {
        protected function _systemToolInfo()
        {
            return [
                'label' => __('Run cron', 'directories'),
                'description' => __('Use this tool to manually run cron.', 'directories'),
                'weight' => 15,
            ];
        }

        public function systemToolRunTask($task, array $settings, $iteration, $total, array &$storage, array &$logs)
        {
            $this->_application->callHelper('System_Cron', [&$logs, true]);

            return 1;
        }
    }

and
namespace SabaiApps\Directories\Component\System\Helper;

use SabaiApps\Directories\Application;

class CronHelper
{
    public function help(Application $application, array &$logs = null, $force)
    {
        // Init progress
        if (!isset($logs)) {
            $logs = ['success' => [], 'error' => [], 'warning' => [], 'info' => []];
            $log = true;
        }
        $logs['info'][] = __('Running cron...', 'directories');
        // Get timestamp of last cron
        $last_run = $application->getPlatform()->getOption('system_cron_last');
        if (!is_array($last_run)) {
            $last_run = ['' => time()];
        } else {
            $logs['info'][] = sprintf(
                __('Cron was last run at %s', 'directories'),
                $application->System_Date_datetime($last_run[''])
            );
        }
        // Invoke cron
        $application->Action('system_cron', [&$logs, &$last_run, $force]);
        // Save timestamp
        $application->getPlatform()->setOption('system_cron_last', $last_run);
        // Log
        if (!empty($log)) {
            foreach (array_keys($logs) as $level) {
                foreach ((array)$logs[$level] as $log) {
                    switch ($level) {
                        case 'success':
                            $application->logDebug(strip_tags($log));
                            break;
                        case 'info':
                        case 'notice':
                            $application->logNotice(strip_tags($log));
                            break;
                        case 'warning':
                            $application->logWarning(strip_tags($log));
                            break;
                        case 'error':
                            $application->logError(strip_tags($log));
                            break;
                        default:
                    }
                }
            }
        }
    }
}

More background information: That Button force runs a Cron Job. And I want to Create a Cron Job, which runs the 'force Cron Job' function.
Let me know if you need more information.
Many thanks


text:
Q: displaying jsHint and cssLint results in sonar jsHint and cssLint can output their results in to standard xml (sjlint.xml and csslint.xml format) file.
Is there a way to display those results with sonar?
What I'm trying to do is to run a jenkins job that will run validations on java script and show the results in Sonar.
Thank you.

A: I think that you need to develop a new Sonar Plugin. Take a look at the following links that might help you.

*

*http://docs.codehaus.org/display/SONAR/Developing+Plugins

*http://docs.codehaus.org/display/SONAR/Plugin+hosting
Digging around, I found this closed Sonar issue suggesting that Sonar's Javascript plugin works better, compared to jsLint:

*

*SONARPLUGINS-1829


text:
Q: blur all elements except one in a div I am trying to blur all elements in a div except one.
I have looked at many similar questions like this one and I get this:
.table-responsive:not(.confirm) {
    filter: blur(3px);
    pointer-events: none;
}

This is basically supposed to blur all elements except the confirm class. Here is a js fiddle demonstrating it: https://jsfiddle.net/qbuyuhts/1/
It's some janky html but does the job to show the problem. Does anyone know why the .confirm div is blurring?

A:
.table-responsive:not(.confirm) { selects element that have class .table-responsive and have not class .confirm this is wrong ,because .confirm is children of .table-responsive.

So change your code like this:
.table-responsive table, .table-responsive div:not(.confirm) {
    filter: blur(3px);
     pointer-events: none;
}

.table-responsive table, .table-responsive div:not(.confirm) {
  filter: blur(3px);
  pointer-events: none;
}

Are you sure?

    <button style="background-color:black;color:blue">Cancel</button>
    <button style="background-color:black;color:blue">Confirm</button>

        <button>Remove</button>
        <button>Edit</button>

{{ course }}
{{ sections }}


text:
Q: Using .hasNext() to loop an input pair I'm new to Java and attempting this question where I'm supposed to input a pair of values (two strings one at a time) which is meant to loop until I've exited using ctrl z. Only the grade will be used for the switch; the name is just a dummy value.
My expected output will be:
Enter name: (Name is then entered)
Enter grade: (Grade is then entered)
Code repeats until EOC is hit.
What is the most effective way to implement a working loop using while (.hasNext())? The code I've tried to make is very flawed, as seen below.
public static void main(String[] args) {

int ACount = 0;
int BCount = 0;
int CCount = 0;
int DCount = 0;

Scanner input = new Scanner(System.in);

    while(input.hasNext()) {
        System.out.print("\nEnter name: ");
            String nameInput = input.next();

        System.out.print("Enter grade: ");
            String gradeInput = input.next();

switch (gradeInput) {
                case "A":
                    ACount++;
                    break;
                case "B":
                    BCount++;
                    break;
                case "C":
                    CCount++;
                    break;
                case "D":
                    DCount++;
                    break;
        }

    }

    System.out.printf("%n%nGrade report%n%nA: %d%nB: %d%nC: %d%nD: %d%n", ACount, BCount, CCount, DCount);

}

A: I think this solution is what you are looking for, it switches between asking for the name and grade until you cancel it with ctrl + z. Personally I have been coding java for 4 years and never used a switch, so I just used simple if-else statements, also by using just print, not println, the phrase was getting into the var, which is the reason of me using println.
public static void main(String[] args) {
    int ACount = 0;
    int BCount = 0;
    int CCount = 0;
    int DCount = 0;

    Scanner input = new Scanner(System.in);
    boolean askingForName = false;
    boolean first = true;
    System.out.println("Enter name: ");
    while(true) {
        if (first) {
            String nameInput = input.nextLine();

            first = false;
            continue;
        }
        if (askingForName) {
             System.out.println("Enter name: ");
                String nameInput = input.nextLine();
                askingForName = false;

        }else {
            System.out.println("Enter grade: ");
            String gradeInput = input.nextLine();

            if (gradeInput.equalsIgnoreCase("A")) {
                ACount++;

            }else if (gradeInput.equalsIgnoreCase("B")) {
                BCount++;
            }else if (gradeInput.equalsIgnoreCase("C")) {
                CCount++;
            }else if (gradeInput.equalsIgnoreCase("D")) {
                DCount++;
            }

             askingForName = true;
        }

        if (!input.hasNextLine())
            break;

    }
     System.out.printf("%n%nGrade report%n%nA: %d%nB: %d%nC: %d%nD: %d%n", ACount, BCount, CCount, DCount);
}


text:
Q: building apk of an android project via command line fails after including some library projects Building the apk for my project fails because ant is searching for the build.xml for the library nineoldandroid.
here's the shell script http://pastebin.com/fhcj9GKG
Tried finding for a way to create build.xml for the library project but failed.
I also tried ant clean, android update and also tried doing it on both windows and linux, computer restart,update adt and other methods but failed to fix the problem. This error appeared after including library projects on my main project.
note : im using adt's ant, i also tried building it without running adt just in case there is a conflict when using ant by two processes but same error appears.
Any idea how to fix this?
Thanks!

A: This will create the missing build.xml:
cd /home/jisidro/ws/temp/NineOldAndroid/
path/to/sdk/tools/android update project --path /home/jisidro/ws/temp/NineOldAndroid/ --subprojects


text:
Q: Is "between __ or __" valid? Today I heard somebody say:

This (technology) can be the difference between life or death.

And I winced.  While "life or death" can be used as an adjective (e.g., modifying "situation" or "decision"), I believe that "between X or Y" is wrong, because "between" should always be used with "and". (Or an implied "and" , as in "between jobs".)
Is "between X or Y" ever acceptable?

A: You are in good company in wincing at between ... or.
Garner in Modern American Usage (p103) calls the construction "a misuse that probably results from confusion between between ... and and either ... or."
Follett in Modern American Usage (p120) calls the combination of between and or  "misguided".
Fowler in Modern English Usage (p57) states: "where terms are separately specified, the one and only right connexion between those terms is and."
As to whether the combination is ever acceptable, Fowler states;

Extenuating circumstances can be pleaded only when one or each of the
  terms is a compound and has its parts connected by and.

A: The Free Online Dictionary lists Life and Death as a variant of Life or Death.
To my mind, when we use words like  difference between, the usage should be life and death.
Here are two different usages:

Cancer patient says he is being made to make life or death decision after health plan cancelled.
  (Headline from a news website)

another way of saying this could be:

Cancer patient says he is being made to make a decision between life and death after health plan cancellation.


text:
Q: How to deal with redundant data within a sample when calculating the standard error? In my research, I analyse pixel data from a 2D microscope image. Each pixel represents a unique spatial position. In my image, each pixel $i$ has a corresponding brightness value $x_i$. I assume the image is representative of the entire potential imaging area.
I want to take the mean and provide an appropriate measure for the error of the mean (presumably the standard error + confidence interval) in order to provide the reader with a measure of how reliable value is if I repeated the measurement in a different imaging area. So for a $10\times10$ pixel image I would average over $100$ pixels to receive a sample mean and a standard error.
Experimentally, I am able to increase my pixel size arbitrarily. That means I can image the same area, but with a higher pixel count, e.g. $100\times100$. However, at some point my pixel size becomes smaller than the theoretical spatial limit that my microscope can resolve. This is what my field refers to as oversampling.
My question stems from the following observation. As I increase my pixel size, I increase my sample size because I treat each pixel as an individual data point. Therefore my standard error drops because it is defined as:
$SE = \frac{s}{\sqrt{n}}$
with the sample standard deviation $s$ and the sample size/pixel count $n$. But because I cannot resolve below a certain threshold I am actually not obtaining additional data. I may be effectively measuring the same point multiple times. So it seems like I am artificially reducing my standard error.
If I had to come up with an explanation it would be: My method for estimating the mean and its error is based on the assumption that each element within my sample is independent because they are spatially apart. As I increase my pixel size, I am reducing my spatial separation and therefore the elements within my sample become increasingly dependant. My method is not made to deal with dependent data.
So my question is, how do I deal with this redundancy of data within my sample? How can I include and acknowledge oversampling in my error estimate? Or is this the wrong approach?