text:
Q: Annotation definition with multiple parameters There are two parameters in the definition, value and optional.
but in the usage, there is only one parameter, so I have two questions:

*

*If there are less parameters in usage than in definition, and the parameter name is absent, how to determine which one is used?

*In the above code, value is an array type, but AuthRequired.AuthType.Server is an element, how can they match?
There is an annotation definition:
Java Code:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthRequired {
    enum AuthType {
        Server(null),
        Student(UserType.Student),
        Teacher(UserType.Teacher),
        SchoolMaster(UserType.SchoolMaster),
        Operator(UserType.Operator);

        private UserType userType;

        AuthType(UserType userType) {
            this.userType = userType;
        }

        public UserType getUserType() {
            return userType;
        }
    }

    AuthType[] value() default {};

    boolean optional() default false;

}

And its usage:
Java Code:
@AuthRequired(AuthRequired.AuthType.Server)
@RequestMapping(method = RequestMethod.GET, value = "/isUserSlaveOf")
boolean isUserSlaveOf(
@RequestParam String slaveUserIds,
...
...

A: *

*If you do not specify the parameter name, it's always the value parameter that's used. Also this is only legal, if you specify a single parameter. Otherwise you need to use <parameterName>=<value> for each parameter.

*Instead of specifying a single element array using the {} bracket notation you are also allowed to simply write the element. @AuthRequired(value=AuthRequired.AuthType.Server) is equivalent to @AuthRequired(value={AuthRequired.AuthType.Server}).


text:
Q: Flutter: How to build a Photo Gallery with Photos stored in the ApplicationDocumentsDirectory? Hi i found it quite surprising when I found not much information about this topic on stackoverflow and the internet.
I try to build a Photo Gallery similar to this:
Go Gallery Gif (source https://www.youtube.com/watch?v=yVS56cLJDgU)
The user can take pictures and I only want to show the pictures in the gallery which were taken with my App.
So here is what I did:
This is the Entity which will be stored to the objectbox-database.
PhotoEntity.dart
@Entity()
class PhotoEntity {
  int id;
  String description;
  String photoPath;
  @Property(type: PropertyType.date)
  @Index()
  DateTime date;

  PhotoEntity(
      {this.id = 0,
      this.description = 'no description',
      required this.photoPath,
      required this.date});

  ImageProvider getImageProvider() {
    return FileImage(File(photoPath));
  }
}

Here is a helper class to communicate with the objectbox-databse
DatabaseController.dart
/*
 * Singleton for Database
 *
 * NOTE: Before using the DatabaseController wait for its initialization with:
 * await DatabaseController().initializationDone;
 */

class DatabaseController {
  // create Singleton instance DatabaseController
  static final DatabaseController _controller = DatabaseController._internal();

  // variable for waiting on initialization
  late Future _initialized;

  Future get initializationDone => _initialized;

  Store? _store;

  late Box<PhotoEntity> boxPhotoEntity;

  Query<PhotoEntity>? _allPhotoEntitiesQuery;
  Stream<Query<PhotoEntity>>? _allPhotoEntitiesQueryWatched;

  DatabaseController._internal() {
    _initialized = create();
  }

  factory DatabaseController() {
    return _controller;
  }

  Future<void> create() async {
    _store = await openStore();

    boxPhotoEntity = _store!.box<PhotoEntity>();
    _allPhotoEntitiesQuery = boxPhotoEntity.query().build();
    _allPhotoEntitiesQueryWatched = boxPhotoEntity.query().watch().asBroadcastStream();
  }

  void close() {
    _store?.close();
    _store = null;
  }

  void addOrUpdatePhotoEntity(PhotoEntity photoEntity) {
    _storeNullCheck();
    boxPhotoEntity .put(photoEntity);
  }

  List<PhotoEntity> getAllPhotoEntities() {
    _storeNullCheck();
    return _allPhotoEntitiesQuery!.find();
  }

  Stream<Query<PhotoEntity>> watchPhotoEntities() {
    _storeNullCheck();
    return _allPhotoEntitiesQueryWatched!;
  }

  Query<PhotoEntity> getAllPhotoEntitiesQuery() {
    _storeNullCheck();
    return _allPhotoEntitiesQuery!;
  }

  void _storeNullCheck() {
    if (_store == null) {
      if (kDebugMode) {
        print(
            'ERROR - you should call DatabaseController.create() before using it OR you shouldnt use the controller after closing it!');
      }
    }
  }
}

Once the user has taken an Image it gets stored to the ApplicationDocumentsDirectory and a PhotoEntity with the correspoing path gets stored in the objectbox-database.
For displaying the Gallery I use a StreamBuilder in order to get notified and update the Gallery accordingly once changes were made to the database.
late Stream<Query<PhotoEntity>> queryStream;

@override
void initState() {
  queryStream = DatabaseController().watchPhotoEntities();
  super.initState();
}

@override
Widget build(BuildContext context) {
  return StreamBuilder(
      initialData: DatabaseController().getAllPhotoEntitiesQuery(),
      stream: queryStream,
      builder: (context, AsyncSnapshot<Query<PhotoEntity>> snapshot) {
        if (snapshot.hasError) {
          return Center(child: Text('Error ${snapshot.error}'));
        }

        if (!snapshot.hasData) {
          return const Center(child: Text('No data'));
        }

        return const GalleryGridView();
      },
  );
}

The GalleryGridView looks like this (and here is the problem):
@override
Widget build(BuildContext context) {
  List<PhotoEntity> photoEntities = DatabaseController().getAllPhotoEntities();

  return GridView.builder(
    itemBuilder: (BuildContext context, int index) {
      return Image(image: photoEntities[index].getImageProvider());
    },
    gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: 150,
        childAspectRatio: 3 / 2,
        crossAxisSpacing: 20,
        mainAxisSpacing: 20),
  );
}

DatabaseController().getAllPhotoEntities() which returns every single PhotoEntity in the database takes obviously way too much memory and time to return.
So what are my possibilities to implement the desired behaviour?
Some thoughts I had about this:

*

*With objectbox I can get all the PhotoEntities as a stream. But how do I turn a stream into a GridView?

*objectbox offers to set an offset and a limit before calling find(). How would I implement a Widget that makes use of that in order to achieve pagination?

It would be very kind if someone would take the time and give me some advise. I have the feeling that I'm missing something very obvious because I would assume this is a very common usecase.

A: Is your question about turning a stream into a widget in Flutter? In that case you need to use StreamBuilder!

redpajama_set_name: RedPajamaStackExchange


text:
Q: pdftk fill_form utf8 problems
Possible Duplicate:
Flatten FDF / XFDF forms to PDF in PHP with utf-8 characters

I am using pdftk to fill template pdf with data from fdf.  Data has correct utf-8 characters, but when I use fill_form, resulting pdf file has formating errors. (I am NOT using flatten)
I have problems with letters like š, đ, č, ć, ž.
Thanks.
UPDATE
My solution
In the end, I gave up on pdftk, I ended up using fpfd, to be more precise, I used this script.
I had couple of problems here too, related to the pdf file. But I used pdftk to fix that pdf (as was suggested in the script itself), and in the end it helped me: it filled the pdf form I had with the characters without messing them up.

A: pdftk (as of v1.44) can't handle chars outside the standard ASCII with FDF form fill. Someone did try to modify pdftk to allow multi-byte characters to support Asian languages, but from the comments I'm not sure it actually works.
http://blog.rubypdf.com/2007/07/19/pdftk-supports-chinese-path-now/
Related Questions:
Flatten FDF / XFDF forms to PDF in PHP with utf-8 characters
pdftk + xfdf + php can't handle umlauts


text:
Q: Как принимать платежи в TelegramBot на java с использованием SpringBoot? Написан рабочий бот на Java, с использованием библиотеки telegrambots-spring-boot-starter.
Не могу разобраться как реализовать метод sendInvoice. Чтобы выставить счет нужно сформировать запрос как я понимаю, но каким способом?
    SendInvoice invoice = new SendInvoice();
    invoice.setProviderToken("provider_token");
    invoice.setChatId(String.valueOf(chatId));
    invoice.setTitle("Платный пакет");
    invoice.setDescription("В платном пакете, сожержиться множество вопросов и заданий.");
    invoice.setCurrency("UAH");
    invoice.setPayload("{\"code\":\"UAH\",\"title\":\"Ukrainian}");

Этот объект служит для формирования Json, который нужно передать в запросе на сервер телеграма. И вот на этоп этапе не пойму, каким способом его передать и получить ответ. В документации о данном api ничего не нашел.


text:
Q: Converting string text to same binary data in python I was trying to read some values from an XML file, say the values represent the reset state of a hardware register. The <Field_Reset_Value>10</Field_Reset_Value> represent two bits here as "1" and "0" respectively. I need to use these values to shift and bitwise or with other bit values further.
Now when I read the value, it is represented as a string. Can someone suggest the way, I can convert string to binary. Say as the example below.
string = "10"

Now I want to convert its binary value as binval = 0b10.
Also, these values can be of any number of bits from 1 to 32 bit. What I mean is the string can also be 1101001110011 so I will need to represent it as 0b1101001110011

A: You can use the following code:
>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'


text:
Q: Prevent stemming of words starting with # in PostgreSQL full text search Basically, I want to be able to get an exact match (hashtag included) for queries like this:
=#SELECT to_tsvector('english', '#adoption');
 to_tsvector
-------------
 'adopt':1

Instead, I want for words starting with #, to see:
=#SELECT to_tsvector('english', '#adoption');
 to_tsvector
-------------
 '#adoption':1

Is this possible with psql full text search?

A: Before you search or index, you could replace each # character with some other character that you don't use in your texts, but which changes the parser's interpretation:
test=> SELECT alias, lexemes FROM ts_debug('english', '#adoption');
┌───────────┬─────────┐
│   alias   │ lexemes │
├───────────┼─────────┤
│ blank     │         │
│ asciiword │ {adopt} │
└───────────┴─────────┘
(2 rows)

test=> SELECT alias, lexemes FROM ts_debug('english', '/adoption');
┌───────┬─────────────┐
│ alias │   lexemes   │
├───────┼─────────────┤
│ file  │ {/adoption} │
└───────┴─────────────┘
(1 row)


text:
Q: Assigning a value to a variable passed to a function causes a segmentation fault. Consider this simple program:
  program foo
  integer bar,idum

  print * , bar(1)
  end program

  function bar(idum)
      integer idum,bar
      print * , idum
      idum =  2
      bar =  2
      return
  end

When I run it, I get a segmentation fault upon the line idum = 2
Starting program: /tmp/a.out
           1

Program received signal SIGSEGV, Segmentation fault.
0x000000000040081b in bar (idum=1) at play.f:11
11            idum =  2

Am I not allowed to assign values to variables passed to a function? how can I use them as flags?

A: You pass a literal value 1 to the function. Then you try to change it in
idum =  2

That is not allowed. The code tries to change the literal constant and crashes, because that is not possible.
If you want to change a value inside a function, then a) it must be a variable, not a constant value, b) it must be passed by value (Fortran 2003).
In modern Fortran always use explicit interfaces. I mean ALWAYS. Either use modules (preferred!!!), or, in simple cases, use internal functions like:
  program foo
    integer bar,idum

    print * , bar(1)

  contains

    function bar(idum)
      integer idum,bar
      print * , idum
      idum =  2
      bar =  2
      return
    end function
  end program

The compiler may be able to tell you you are doing it wrong. Especially so, if you specify intent for the argument:
function bar(idum)
   integer bar
   integer, intent(in) :: idum

The compiler will complain now. It will also complain with other intent's.  And you can then fix the code to make the compiler happy.
And ALWAYS!!!!! use IMPLICIT NONE. This is not optional. It is necessary.


text:
Q: Xubuntu 14.04 setting Primary Monitors I'm using Xubuntu 14.04 with the 331.38 drivers that I installed via the "Additional Drivers"
My issue is that when ever I start up a game it starts up in the wrong monitor, to fix this I when my computer starts I set the primary monitor in the Nvidia settings manager.. the only problem is every reboot it looses the setting of the primary monitor... and I have to keep setting this every time.
I notice there is no more Xorg file... so how would I fix this seeing that the Display settings of XFCE is not able to set "Primary Monitor"

A: use xrandr and find the display you want to set as primary, then
in your .bashrc add the command
xrandr --output [DISPLAY DEVINCE] --primary

Example:
xrandr --output DP-1 --primary

this is the same as going into the nvidia-settings app and applying a primary monitor.
log out and log back in, and you should see that your primary monitor is set correctly.


text:
Q: How to HIDE everything in PUBLISH metabox except Move to Trash & PUBLISH button I have a custom post type (called contacts).
Since this post type is not working like a post, I don't want to show SAVE DRAFT, PREVIEW, Status, Visibility or Publish Date.
The only options I want to show are PUBLISH & Move to Trash buttons.
Is there a way to hide these other options? If not, how do I create a new PUBLISH & Move to Trash that I can add to a new metabox?

A: You can simply hide the options using CSS. This will add a display:none style to the misc and minor publishing actions on the post.php and post-new.php pages. It checks for a specific post type as well since all post types use these two files.
function hide_publishing_actions(){
        $my_post_type = 'POST_TYPE';
        global $post;
        if($post->post_type == $my_post_type){
            echo '
                <style type="text/css">
                    #misc-publishing-actions,
                    #minor-publishing-actions{
                        display:none;
                    }
                </style>
            ';
        }
}
add_action('admin_head-post.php', 'hide_publishing_actions');
add_action('admin_head-post-new.php', 'hide_publishing_actions');

A: In this example you can easily set on which post types you want to hide the publishing options, the example hides them for the build-in pots type type page and the custom post type cpt_portfolio.
/**
 * Hides with CSS the publishing options for the types page and cpt_portfolio
 */
function wpse_36118_hide_minor_publishing() {
    $screen = get_current_screen();
    if( in_array( $screen->id, array( 'page', 'cpt_portfolio' ) ) ) {
        echo '<style>#minor-publishing { display: none; }</style>';
    }
}

// Hook to admin_head for the CSS to be applied earlier
add_action( 'admin_head', 'wpse_36118_hide_minor_publishing' );

Important update
I would also suggest you force a post status of "Published" to avoid saving posts as drafts:
/**
 * Sets the post status to published
 */
function wpse_36118_force_published( $post ) {
    if( 'trash' !== $post[ 'post_status' ] ) { /* We still want to use the trash */
        if( in_array( $post[ 'post_type' ], array( 'page', 'cpt_portfolio' ) ) ) {
            $post['post_status'] = 'publish';
        }
        return $post;
    }
}

// Hook to wp_insert_post_data
add_filter( 'wp_insert_post_data', 'wpse_36118_force_published' );


text:
Q: UITableView in Swift - dequeueing of cells func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int {
    return 5
}

func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
        let cell = tableView.dequeueReusableCellWithIdentifier("BookCell") as BookTableViewCell

        println("ip: \(indexPath.row)")
        cell.bookLabel.text = "Row #\(indexPath.row)"

        return cell
    }

I just see one cell, with the text overwritten 5 times, instead of 5 cells. I thought we didn't have to do the if (!cell) nonsense anymore? What am I doing wrong?

A: If you are seeing the UILabels overwritten 5 times, it is because your cell height has not been defined and it is being computed as 0 pixels tall. Any one of the following should help you explicitly or implicitly define the row height:
1) Set the row height within Interface Builder:

2) Implement the UITableViewDataSource protocol method:
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
    return 50.0
}

3) Set Auto Layout constraints between your cell's UILabel and the outer boundaries of the UITableViewCell:


text:
Q: Neo4j Aura demo python AttributeError: 'Session' object has no attribute 'execute_write' In the Aura Python connection code, I have an issue with getting
attributeError: 'Session' object has no attribute 'execute_write' / 'execute_read' in
line 17    result = session.execute_write
line 44    result = session.execute_read

A: I have resolved this by replacing the
execute_write with write_transaction
execute_read with read_transaction
result = session.write_transaction(
result = session.read_transaction(


text:
Q: cmd or powershell command from html with no window is there a way to active a powershell or a cmd command from html file without opening a console window ?
for example the following code runs the l.bat file i have without showing the output but still there is a powershell window which is open while the file runs
code:
<OBJECT id=z classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11" width=5 height=5>
<PARAM name="Command" value="ShortCut">
<PARAM name="Button" value="Bitmap::shortcut">
<PARAM name="Item1" value=",powershell.exe ,Start-Process &#45WindowStyle hidden 'l'">
</OBJECT>

any idea?

A: if you want run script or bat file in html file or in ur site want run script
you can use visual studio and add  Web Application called PowerShellExecution
default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PowerShellExecution.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

<form id="form1" runat="server">

PowerShell Command Harness

 	PowerShell Command

                <asp:TextBox ID="Input" runat="server" TextMode="MultiLine" Width="433px" Height="73px" ></asp:TextBox>

                <asp:Button ID="ExecuteCode" runat="server" Text="Execute" Width="200" onclick="ExecuteCode_Click" />

Result

                    <asp:TextBox ID="ResultBox" TextMode="MultiLine" Width="700" Height="200" runat="server"></asp:TextBox>

</form>

Tools menu select Library Package Manager >> Package Manager Console
Package Manager Console execute "Install-Package System.Management.Automation"
After a successful execution of that package install, you'll want to add the reference to your Default.aspx.cs file:
using System.Management.Automation;

in ur Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Text;

namespace PowerShellExecution
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ExecuteCode_Click(object sender, EventArgs e)
        {
            // Clean the Result TextBox
            ResultBox.Text = string.Empty;

            // Initialize PowerShell engine
            var shell = PowerShell.Create();

            // Add the script to the PowerShell object
            shell.Commands.AddScript(Input.Text);

            // Execute the script
            var results = shell.Invoke();

            // display results, with BaseObject converted to string
            // Note : use |out-string for console-like output
            if (results.Count > 0)
            {
                // We use a string builder ton create our result text
                var builder = new StringBuilder();

                foreach (var psObject in results)
                {
                    // Convert the Base Object to a string and append it to the string builder.
                    // Add \r\n for line breaks
                    builder.Append(psObject.BaseObject.ToString() + "\r\n");
                }

                // Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
                ResultBox.Text = Server.HtmlEncode(builder.ToString());
            }
        }
    }
}

"PowerShell Command" window Get-EventLog Security -Newest 10 (or your favorite cmdlet for a test).
or put script on that just change
//shell.Commands.AddScript(Input.Text);
shell.Commands.AddScript("C:\\Scripts\\PowerShell\\PowerShellScript.ps1")

but for run script you should run
Set-ExecutionPolicy bypass
in your powershell 32 bit and 64 bit
64 bit
 C:\Windows\System32\WindowsPowerShell\v1.0

32 bit
C:\Windows\SysWOW64\WindowsPowerShell\v1.0

you should run visual studio and publish in your iis very simple to add feature iis
for dns you can use
C:\Windows\System32\drivers\etc

in host file like
127.0.0.1 soheil.com

I hope i understand ur needs
Regards


text:
Q: android 12 onBackPressed Android 12 has changed behavior for back button. However, sometimes the behavior is confusing. For example, when I press it, my app does not go away (onResume is called right after onPause); other times, when I press it, my app goes away but a previously used app is opened. Other times, when I press it, my app goes away as expected (as with older versions of Android).
I've seen this behavior with other apps too. For example: the default "Files" app in Google Pixel 3a.
Is it a bug? or can I do something in my app to have always the expected behavior (as with older versions of Android)? Thanks a lot for your time.

A: Overriding onBackPressed in your launcher activity and calling finish in it would ensure your app always behaves as with older versions of Android.


text:
Q: A page that shows a list of a specific custom post type I've created a custom post type called 'product'.  I want to add a page link to 'products' in the menu, but I don't have that option.
I would like to know if there is a way of displaying it the same way as if it were like a category...
a page that shows all the 'products' like if they were posts, and that I could add to the menu.
At this stage I can only add specific 'products' but not a link to a list of them.
Any suggestions on how to make this work?

A: What you are looking for is custom post type archive. First you should make sure that your CPT is registered to have archive at all.
Unfortunately natively WP doesn't add CPT archives as available to be included in menus. The simplest solution is just to add custom link to it.
There are also multiple snippets and plugins to address this floating around, from quick look up I have Post Type Archive Link bookmarked.

A: In addition to @Rarsts answer, once you've created a custom post type with archive like this example:
//* Create product custom post type
add_action( 'init', 'register_product_custom_post_type' );
function register_product_custom_post_type() {

register_post_type( 'product',
    array(
        'labels' => array(
            'name'          => __( 'Product', 'wpsites' ),
            'singular_name' => __( 'Product', 'wpsites' ),
        ),
        'has_archive'  => true,
        'hierarchical' => true,
        'menu_icon'    => 'dashicons-portfolio',
        'public'       => true,
        'rewrite'      => array( 'slug' => 'product', 'with_front' => false ),
        'supports'     => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'revisions', 'page-attributes' ),
        'taxonomies'   => array( 'product-type' ),

    ));

}

You can also control that archive using pre_get_posts.
add_action( 'pre_get_posts', 'customize_custom_post_type_archive' );

function customize_custom_post_type_archive( $query ) {
if ( is_post_type_archive('product') && $query->is_main_query() )

    $query->set( 'posts_per_page', '6' );
    $query->set( 'order', 'ASC' );
return $query;
}

You can then add your CPT archive link as a custom URL to your menu
http://example.com/product/


text:
Q: Continuous mapping theorem and convergence in $L_p$ My question kind of generalizes the question in Analogue of continuous mapping theorem for convergence in $L_2$
and it is related to the answer by Nate Eldredge.
Edited to give more details:
Suppose that
\begin{equation}\tag{1}\label{eq1}
E|X_n - X|^p = O(b_{p,n}),
\end{equation}
where $p \geq 1$ and $b_{p,n} \to 0$ as $n \to \infty$. Furthermore, assume that there exist constants $0 < a < b < \infty$ such that $a \leq X_n \leq b $ a.e. and $a \leq X \leq b$ a.e.
Now, let $g$ be a continuous function with the following property: there exists a constant $C>0$ where $\sup_{x\in(a,b)}|g(x)| < C$. For example, $g(x) = x^r$, $r>0$, is a possible function. In this case, what can I say about $E|g(X_n) - g(X)|^p$, $p\geq1$? Is it possible to find a rate of convergence based on \eqref{eq1} and the above mentioned assumptions?
In a more specific case, is it possible to find the rate of convergence for $E|X_n^r - X^r|^p$, with $r > 0$ and $p \geq 1$, assuming \eqref{eq1} and that $a < X_n < b$ a.e. and $a<X<b$ a.e.?
Since $a < X_n < b$ a.e. and $a<X<b$ a.e., I think that I can assume, as discussed by Nate, that $L_p$ convergence is guaranteed (we have that $g(X_n) \to g(X)$ in measure by the continuous mapping theorem, and in $L_p$ by the dominated convergence theorem), but I could not find any rate of convergence in my problem.
Thanks in advance.

A: Since a continuous function on a compact set is Lipschitz,
$$
\mathsf{E}|g(X_n)-g(X)|^p\le L^p\mathsf{E}|X_n-X|^p=O(b_{p,n}),
$$
where $L$ is the corresponding Lipschitz constant.


text:
Q: Почему WP_Query paged возвращает 1 для всех страниц? Делаю шаблон страницы результатов поиска search.php
И столкнулся с проблемой. Не работает пагинация.
А именно, как я понимаю, не определяется номер текущей страницы.
WP_Query paged всегда равно 1.
При приклике на пагинацию, ссылка формируется вроде правильно ( /page/2/?s=поисковой запрос )
но записи не меняются.
Вот мой код:
<?php

    $thesearch = get_search_query();

    $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

    $args = array(
        'post_type' => 'post',
                's' => $thesearch,
                'posts_per_page' => 20,
                'meta_key' => '_thumbnail_id',
                  array(
                    'key' => '_thumbnail_id',
                    'compare' => 'EXISTS'
                  ),

                'paged' => $paged
            );

    $the_query = new WP_Query( $args );

?>

<?php if ($the_query->have_posts()) : ?>

Пагинация стандартная the_posts_pagination(  );


text:
Q: Building Stored Procedure for DB2 for IBM i (iSeries) through Data Studio fails When trying to Deploy a Stored Procedure for DB2 on IBM i (an iSeries) through Data Studio, it says "No Build Services found for routine." in the status window.
I see options in preferences->Data Management->SQL Development->Routines->Deploy Options->SQL - External.  By default this is populated with Build utility name: DSNTPSMP, in SYSPROC schema, but that is not something that exists in iSeries.  Does anyone know the equivalent schema and program for that on an iSeries?

A: That setting is for deploying to z/OS, not IBM i.  Generally speaking, an External SQL routine on IBM i is an HLL, like RPG or Cobol that you'd create separately, and then issue the SQL 'CREATE PROCEDURE' statement to register the program as a stored procedure to DB2 for i.


text:
Q: How to find $\lim_{n \to \infty}\Sigma_{i=1}^n\frac{\sin(\pi x)^2}{i^2}$? I am trying to find:
$$\lim_{n \to \infty}\sum_{i=1}^n\cfrac{\sin(\pi x)^2}{i^2}$$
using maple command:
limit(Sum(sin(Pi*x)^2/i^2, i = 1 .. n), n = infinity);
gives:
$\cfrac{1}{6} \left( \sin \left( \pi \,x \right)  \right) ^{2}{\pi }^{2}$
How to find $\lim_{n \to \infty}\Sigma_{i=1}^n\frac{\sin(\pi x)^2}{i^2}$?

A: If you have an $x$ in the sum with $\sin(\pi x)^2$ ,it will just get out of the Summation. Thus,
$$\lim_{n \to \infty}\Sigma_{i=1}^n\frac{\sin(\pi x)^2}{i^2}$$
$$=\sin(\pi x)^2\lim_{n \to \infty}\Sigma_{i=1}^n\frac{1}{i^2}$$
$$= \frac{π^2×\sin(\pi x)^2}{6}$$
If you mean $\sin(\pi \color{red}{i})^2$ instead,
$\sin(\pi \color{red}{i})^2 = 0  \forall i \in N $. So
$$\lim_{n \to \infty}\Sigma_{i=1}^n\frac{\sin(\pi i)^2}{i^2} = 0$$

A: Note that:
$$\lim_{n\to\infty}\sum_{i=1}^n\frac{\sin^2(\pi x)}{i^2}=\sin^2(\pi x)\sum_{i=1}^\infty\frac{1}{i^2}=\frac{\pi^2}{6}\sin^2(\pi x)$$
since:
$$\sum_{i=1}^\infty\frac{1}{i^2}=\zeta(2)=\frac{\pi^2}{6}$$
Where $\zeta$ is the zeta function


text:
Q: Dotnet new project cannot run I (almost) try to get an helloworld with dotnet cli on Linux. In fact I simply try to create a MVC project.
I installed (and reinstall multiple times during this process) dotnet-sdk-bin from AUR.

*

*dotnet new mvc -n foo

*cd foo/

*dotnet run

Result :

It was not possible to find any compatible framework version
The framework 'Microsoft.AspNetCore.App', version '3.1.0' was not found.

*

*No frameworks were found.
You can resolve the problem by installing the specified framework and/or SDK.
The specified framework can be found at:

*https://aka.ms/dotnet-core-applaunch?framework=Microsoft.AspNetCore.App&>framework_version=3.1.0&arch=x64&rid=manjaro-x64

dotnet --info :

I also tried with and without dotnet-runtim-bin and dotnet-host-bin but the result remain the same. Also found this thread on github but it didn't help me that much.

A: You need to install the runtime to the AspNetCore, I'm sure that you have the runtime to the .NETCORE, but the Asp is a separate runtime and you need to install, I share the URL https://dotnet.microsoft.com/download/dotnet-core/3.1
NOTE: Remember before you type dotnet run is a good practice dotnet build it's help you to find any break references in your code or any lost library.


text:
Q: Combining a React web app with a PCF component I would like to know if it's possible to add a PCF component (written in typescript) to an existing React web app so that when I run the web app, my PCF component will render in the browser.
PCF = Power Platform Component Framework


text:
Q: Unable to run TYPO3 website to localhost Currently I will upload a website to a server, but before I upload it I want to run this website on my localhost (I'm using XAMPP).
They gave me an archive containing the website files, based on the structure of the webfiles I realize TYPO3 is used.
Since I never tried using TYPO3, I tried installing it I followed this steps:
here
 After the installation I run the sample, so far I don't have a problem running it on my web browser.
But when I tried to run the website that I need to upload
I'm getting an error.
here are the files inside the archive.

Here is after I extract it. As you can see I wasn't able to extract typo3_src which is the target location of index.php, t3lib and typo3 file that are all both in .symlink type.
And also the typo3 is not in folder type unlike the sample I run.

I'm not sure if the archive is broken/corrupted or I need something to do first before it will work. Can someone please help me regarding this issue?

A: You do not need to deal with those unix symlinks at all.
Just figure out or ask the person who provided you with that system, which version of TYPO3 you need to use.
Then go to https://sourceforge.net/projects/typo3/files/TYPO3%20Source%20and%20Dummy/ and download the appropriate zip package.
Decompress the package, delete all symlinks (typo3, t3lib, index.php) and just copy the corresponding resources from the package.
You then need to deal with the database and database connection settings in typo3conf/localconf.php or typo3conf/LocalConfiguration.php.
If it all works, you can then upload it like this to the server without using any symlinks.


text:
Q: Linux distribution that offers a good KDE experience I have been a Gnome user for years (8 years), and I'm looking for recommendations and comparisons of Linux distributions that offers good KDE integration/experience. Some details to mention:

*

*the environments speed,

*selection of default apps

*whether it's a modified KDE

*what makes the distro special regarding KDE and KDE/QT apps?

*Employed or active KDE developers who are also distro developers

*integration with gtk apps

*how friendly is it for a novice user (e.g. all cli, do it yourself, or pretty much set up to just work)

Thanks

A: If your into rolling distros there's the new OpenSuSE-Tumbleweed -- OpenSuSE but rolling :-). Other good KDE4 rolling disros include: Aptosid, PCLinuxOS, Yoper, Chakra, Sabayon. Toorox is not 100% rolling but is based on Gentoo. I think all of these are quite newbie friendly and have a big focus on KDE (GUI-centric, "just work", etc).
BTW Mageia (community fork of Mandriva) are in talks on whether to go rolling or not.
If you want DEB, a friend of mine has only good things to say about Aptosid (fka Sidux).
Chakra (based on Arch) is currently still in alpha but has a modular & modifiable KDE allowing you to customize it, optimize it, and remove unwanted bloat.
PCLinuxOS can need a reinstall when they re-fork the Mandriva base every year or so; though with Mandriva's troubles they may switch to Mageia or Unity Linux as their base. They might even go independent but I don't know if they have the devs for that.
I've used Linux Mint-Gnome for the last year (and previously Ubuntu) and I'm about to switch to a rolling KDE4 distro with E17 as my 2nd DE, so I'm in pretty much the same boat as you and would definitely still call my self a "newbie".
BTW I really recommend going rolling: latest software and no reinstalls! I've generally only heard/read good things by those who've tried rolling (though there are always exceptions) and most seem unwilling to switch to any distro that isn't once they've got a taste.

A: I'm liking OpenSUSE 11.3. It seems to have quite a good selection of software available in the repositories, and it seems plenty fast to me (but then, I'm running it on fast hardware, so YMMV).

A: No one's suggested Kubuntu? Kubuntu is by far the best KDE distro. Gnome apps use the correct themes out of the box. I use Kubuntu and have nothing but good things to say.

A: The two mainstream ones with a lot of software would be

*

*fedora

*kUbuntu

A: I've primarily used OpenSuSE, Gentoo, and Arch, and all of them have worked quite well with KDE. However, aside from the fact that Gentoo and Arch are rather more hardcore than OpenSuSE, I believe that both of them use a vanilla version of KDE whereas OpenSuSE adds more of their own stuff, including a really nice KPart for viewing system information (which probably should be added to KDE proper) and increased integration for some non-KDE programs such as Firefox. So, whether OpenSuSE is better than the others is probably a combination of how newbie-friendly a distro you want and whether or not you want a vanilla version of KDE.
The one thing that I can say beyond that is that I frequently hear people say not to use Kubuntu and that it's a poor KDE distro with relatively poor stability. I played around with it a little a while back but not long enough to really be able to comment on that (I really didn't like its package management and found multilib to be much more of a pain than with OpenSuSE, though others may disagree). It is about the main consistent thing that I've heard about KDE distros though: many folks say not to use Kubuntu.
Every distro that I've really used though has been fine for KDE. For the most part, I would think that it's more of a general issue of how a distro works than what it does with KDE - unless you're talking about a gnome-centric distro instead of a more DE-agnostic one, in which case it probably matters more, since KDE wouldn't get as much attention and might be treated as a second-class citizen.

A: I've used a lot of distributions and here's what I know.

*

*OpenSuse

*

*Suse was primarily KDE before it bought novell a long term

*used some KDE 4 code before KDE was released - kickoff and games

*has been known to modify kde

*installs and configures things for gtk for you

*might contribute upstream / have actual kde devs - not 100%

*qt driven apps

*Mandriva

*

*I've never used it (not since it was mandrake)

*I know they assigned 2 devs to work on k3b 2 - lots of bonus points

*Chakra

*

*A distribution based on Arch Linux which is KDE specific

*some custom kde/qt apps

*shaman - qt package manager

*Everyone else - Kubuntu, Fedora, Arch, Gentoo (note: kubuntu, fedora might not be accurate)

*

*AFAIK vanilla KDE installs

*User Friendly's will do the gtk theming for you, the others you do it yourself

*they are unlikely to have any kde/qt (adept excluded) apps that aren't available everywhere

To be honest I might be giving everyone else an unfair accounting... I haven't used kubuntu, or fedora much at all. I use Arch Linux  KDE myself, which follows upstream.

A: Pardus 2011, Kde is primary desktop environment. it is fast, elegant, doesn't spend too much memory, stable, fully integrated with gtk apps(thanks to the new gtk theme). It is really user-friendly( Since it's primary customers are government institutes.)


text:
Q: Prisma with NodeJS I have two databases one is a postgresql going to be created using prisma running the commands
npx prisma db pull
npx prisma generate

The second database is a SQL-SERVER that already exists and has data in it, How can I use prisma to query it?
Is there any configuration that I need to do on prisma on in my application?
I'm using NodeJS for this API.


text:
Q: How to run lines of code everytime you open an application Wanted to know how I can run a couple lines of code everytime I launch an application.
For more detail, I want a message to be sent via discord everytime I launch a certain application. I have figured out how to send the message through discord using python, but have not been able to figure out how to execute this code whenever I open an application


text:
Q: TFJS-converter | How can I convert faster_cnn_inception_v2_coco to tfjs format? While I am trying to convert faster_rcnn_inception_v2_coco saved model to Javascript format, I received an issue:
KeyError: <tf.Tensor 'SecondStagePostprocessor/BatchMultiClassNonMaxSuppresion/map/while/Switch_1:0' shape=<unkknown> dtype=float32>
Environment:
python3.6 , tensorflowjs 1.0.1, MacOS Mojave 10.14.3
Steps to reproduce:

*

*Download faster_rcnn_inception_v2_coco tar and extract it

*Try to convert with

 tensorflowjs_converter --input_format=tf_saved_model --output_format=tfjs_graph_model <pathToExtractedTar>/saved_model ./output_folder

Would you be so kind to suggest some ideas according this issue?
Thank you


text:
Q: How to know the form is being submitted or rendered in model page of set/get method of symfony? I am working on symfony, need to know how can we get the isSubmitted() or similar kind of method in model file which can say like form is submitting/rendering.

A: All form-related tasks should be done into controller. If you want to migrate some code (legit) I suggest not to migrate "form posting status" elsewhere. What you can do is

*

*check for form submission

*pass a flag to your model


text:
Q: Fetch private gitlab repo using ssh with Yocto recipe I am trying to fetch a private gitlab repo within Yocto image recipe using SSH protocol. In my image recipe I have passed SRC_URI as:
SRC_URI = " \
        gitsm://git@git.example.com:2224/blah/blah/blah/blah;protocol=ssh;branch=master \
"

But this results in the error:
ERROR: Fetcher failure: Fetch command export PSEUDO_DISABLED=1; export PATH="/root /build-swu-v2/tmp/sysroots-uninative/x86_64-linux/usr/bin:/root/sources/poky/scripts: /root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/awsclient/1.4- r0/recipe-sysroot-native/usr/bin/arm-poky-linux-gnueabi:/root/build-swu-v2/tmp /work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/awsclient/1.4-r0/recipe-sysroot/usr/bin /crossscripts:/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi /awsclient/1.4-r0/recipe-sysroot-native/usr/sbin:/root/build-swu-v2/tmp/work/cortexa7t2hf- neon-vfpv4-poky-linux-gnueabi/awsclient/1.4-r0/recipe-sysroot-native/usr/bin:/root/build- swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi/awsclient/1.4-r0/recipe-sysroot- native/sbin:/root/build-swu-v2/tmp/work/cortexa7t2hf-neon-vfpv4-poky-linux-gnueabi /awsclient/1.4-r0/recipe-sysroot-native/bin:/root/sources/poky/bitbake/bin:/root/build-swu- v2/tmp/hosttools"; export HOME="/root"; LANG=C git -c core.fsyncobjectfiles=0 clone --bare  --mirror "ssh://git@git.osb-connagtive.com:2224/iot/products/iot-device-suite_client/aws- iot-client" /root/downloads//git2/git@git.example.com:2224/blah/blah/blah/blah --progress failed with exit code 128, no output
ERROR: Bitbake Fetcher Error: FetchError('Unable to fetch URL from any source.',  'gitsm://git@git.example.com:2224/blah/blah/blah/blah;protocol=ssh;branch=master')
DEBUG: Python function base_do_fetch finished

But I am able to clone the repo using git clone.
SSH key is already added to the Gitlab. There is no config file in my ~/.ssh. Do I need to create a config file? What should be the content of the config file?
Update
After following some discussion from other posts, I added "config" file.
~/.ssh/config:
Host git.example.com
HostName git.example.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_ed25519.pub
# LogLevel DEBUG3

Then ssh-add ~/.ssh/id_ed25519.pub
Could not open a connection to your authentication agent.

And ssh -T git@git.example.com
ssh: connect to host git.osb-connagtive.com port 22: Connection refused

Can anyone please let me know how to resolve this?
Thanks in advance.
P.S: I am using Ubuntu 20.04 with Yocto on Dunfell version.

A: SRC_URI = "git://git.example.com:2224/blah/blah.git;protocol=ssh;branch=master"

A: I found a solution to my problem and it is as follows.
My test application is called simpledaemon.
I deleted sources/meta-simpledaemon
I ran the following bitbake commands
bitbake-layers create-layer ../sources/meta-simpledaemon
bitbake-layers add-layer ../sources/meta-simpledaemon
mkdir ../sources/meta-simpledaemon/recipes-example/simpledaemon
recipetool create -V 1.0 git@gitlab.com:MichaelBMiner/simpledaemon.git -o ../sources/meta-simpledaemon/recipes-example/simpledaemon/

Now the problem I had was GitLab be default names your primary branch main, recipe by default looks for master. So I made my primary branch name master and it all worked!


text:
Q: How to view linux kernel logs live? I have a kernel module logging input of some sensor while I work with it. I want to see if there is a command that outputs /var/log/messages (for example) but waits for more logs to come. That is, some program like dmesg except that it stays on and keeps printing newly-come logs.

A: Have you tried tail -F, eg.
tail -F /var/log/messages

A: You can:

*

*execute dmesg every second: while true; do dmesg -c; sleep 1; done

*print everything appended to /var/log/messages: tail -f /var/log/messages

*dump the logs on the serial port and read them on another PC. You will need to add to your kernel boot parameters: console=ttyS0,115200 console=tty0 ignore_loglevel and remove quiet

A: You could use
 cat /proc/kmsg

By this way you could get all kernel messages when they come

A: Two more modern methods:
dmesg -w

On systems with systemd journalctl is also of interest:
journalctl --system -f


text:
Q: Cannot disable password expiry on Server 2012 I have an internal only Windows Server 2012 which I want to disable the password policy on.  (The server is also a domain controller, if that makes any difference.)
I've tried following the instructions on this helpful blog, but when I double click on any of the entries, the control on the properties dialog (to set the value) is disabled.
I'm logged into the server as an administrator, and I've open the Local Security Policy as an administrator.
Can anybody explain why I'm unable to change these values?
(Please be gentle, I'm a programmer, not a network guru.)

A: You're trying to edit this setting using the Local Security Policy editor but the setting is configured in Group Policy and that's where you need to change it.

A: @Joe sent me in the correct direction, and from his comment I found this blog via Google.
The bit in particular which was useful was a comment left on the blog...

On my server, these settings are disabled under the Local Security Policy (WS2012 Essentials.) However, they can be changed under the Group Policies.
From the charms, search Apps for "gpmc.msc" and start it.
  Group Policy Management -> Forest: YourServerName.local -> Domains -> YourServerName.local
  Select "Default Domain Policy" then right-click and select "Edit…" to open the Group Policy Management Editor.
Group Policy Management Editor
  Computer Configuration -> Windows Settings -> Security Settings -> Account Policies -> Password Policy


text:
Q: Как правильно очистить массив кроме первого[0] значения в цикле? У меня есть массив.
items = []
items[0] = {id: "805", category: 'Apple'}
items[1] = {id: "804", category: 'Plum'}
items[2] = {id: "805", category: 'Watermelon'}
items[3] = {id: "804", category: 'Grape'}

function Test {
    var result = '';
    items.forEach(function(item) {
        result += item.category + '\n';
    });
    console.log(result);
}
<button onclick='Test();'>тест</button>

При каждом клике на кнопку вызывается функция, которая выводит в консоль значение category.
Моя проблема заключается в том, что в консоли выводится APPLE - при одном клике на кнопку. При втором - PLUM APPLE, и если на 3 -
WATERMELON PLUM APPLE.

Мне же нужно получить вывод при каждом клике только одного значения. То есть при дальнейшем вызове функции - подтягиваются предудыщие значения. Полагаю что нужно очищать массив, но как это сделать в данном случае ?

A: Вполне можно обойтись без изменений массива при выводе (и без лишних глобальных переменных):

var items = [
  {id: "805", category: 'Apple'},
  {id: "804", category: 'Plum'},
  {id: "805", category: 'Watermelon'},
  {id: "804", category: 'Grape'}
];
var generator = categoryGenerator(items);

function* categoryGenerator(itemsArr) {
  for (let i = 0; i < itemsArr.length; i++)
    yield itemsArr[i].category;
}

function test() {
  let n = generator.next();
  if(n.done === false)
    console.log(n.value);
}
<button onclick='test();'>тест</button>

A: То, что Вы описываете, не может происходить в Вашем коде, если массив items не меняется между нажатиями на кнопку.
Непонятно, какой смысл Вы вкладываете в фразу: "подтягиваются предудыщие значения".

var items = [
  {id: "805", category: 'Apple'},
  {id: "804", category: 'Plum'},
  {id: "805", category: 'Watermelon'},
  {id: "804", category: 'Grape'}
];

var index = 0;
function Test() {
  var result;
  if (index < items.length) {
    result = items[index++].category;
  } else {
    result = "Index is out of range - " + index;
  }
  console.log(result);
}
<button onclick='Test();'>тест</button>

A: если ссылка на массив одна то items  = items[0]; иначе items.length = 1;


text:
Q: How does one use Magento's REST API to run keyword queries? I'm developing a community extension for Magento, when a product search is detected, some JavaScript included with the extension needs to query the Magento API to get a larger number of results than are rendered on page.
I have the API configured, responding, and returning useful data, but I'm struggling to find a way to apply a query to the API call. I've tried adding ?q= or ?keyword= and similar, but it continues to return the same set of data without any filtering applied. Countless passes through Google, Magento StackExchange, and various Magento developer forums haven't made it clear one way or another if this is even possible.
Does the REST API support keyword / phrase searches, or will my extension need to include a block that adds this functionality to the REST API?

A: Did you take a look at Magento API Filtering .
You could also create you own Custom API or Extending the Core API


text:
Q: Jedis error Could not get a resource from the pool I'm currently using jedis version 2.9.0 in my maven webapp. It consists in a loop that retrieves data for caching every five minutes. For that purpose, I'm creating a jedispool on app Scheduler class when the whole app starts the execution. It runs only once on the app start and then never again.
@WebListener
public class appScheduler implements ServletContextListener {

    private static JedisPool jedisPool;

    private ScheduledExecutorService scheduler;

    public void contextInitialized(ServletContextEvent event) {
        logger.info("contextInitialized: " + event);
        logger.info("Creating scheduler for cache updates...");
        boolean loadStatus  = PropertiesLoader.getInstance().load();
        if(!loadStatus){
            logger.error("Error loading properties");
            System.exit(1);
        }
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new UpdateCacheJob(), 1, 5, TimeUnit.MINUTES);

        int port = 6379;
        try {
            port = Integer.parseInt(PropertiesLoader.getInstance().getCachePort());
        } catch (NumberFormatException e) {
            logger.error("Invalid port in properties file for cache.");
        }
        jedisPool = new JedisPool(PropertiesLoader.getInstance().getPoolConfig(), PropertiesLoader.getInstance().getCacheEndpoint(), port);
    }

    public static Jedis getJedisResource() {
        return jedisPool.getResource();
    }
}

My pool configuration:
      final JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(128);
        poolConfig.setMaxIdle(128);
        poolConfig.setMinIdle(16);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setTestWhileIdle(true);
        poolConfig.setMinEvictableIdleTimeMillis(60000);
        poolConfig.setTimeBetweenEvictionRunsMillis(30000);
        poolConfig.setNumTestsPerEvictionRun(3);
        poolConfig.setBlockWhenExhausted(true);
        return poolConfig;

Every five minutes a pipeline is created to sync the new data on cache in a different class:
Jedis jedis = schedulerFunction.getJedisResource(); //retrieve resource from scheduler class

Pipeline pipeline = jedis.pipelined(); //create the pipeline

for (String key : list.keySet()) {
    pipeline.setex(key, 3600, data_to_fill_cache);
}
pipeline.sync(); //sync pipeline
logger.info("Cache synched... ");

Everything works fine for many hours, but then suddenly stops with the following error:
Could not get a resource from the pool
It happens on the line of resource retrieval to create jedis on 5 minutes loop function. It doesn't happen consistently at the same time though. It could either happen after two hours or ten, it's never the same. The pipeline is following the same process every five minutes and writing the same data to redis. It's not a problem of data integrity or a sudden change that could affect the process. I've discarded any other causes. The context have been retrieved hundreds of times before suddenly getting the error.
I've been looking through all documentation on the internet but I have been unable to find a reason or a solution.

A: I think all your resources have been retrieved but none of them are returned.
You would have to return the resources after using them. (If you're using a good enough version of Jedis,) You can return the resource by calling jedis.close(); or try-with-resources.


text:
Q: QTabBar, remove signal tabMoved(from, to) from function moveTab(from, to) As I am connecting a QListWidget to a QTabBar, I see that everytime I drag&drop a tab the signal tabMoved is triggered. This works perfectly.
It seems that even when I execute the function moveTab(from, to), the same signal is triggered. Is it possible to set the function moveTab not to trigger the signal tabMoved(from, to)?

A: I think that will do,
myTabBar.blocksignals(true);
myTabBar.moveTab(from, to);
myTabBar.blocksignals(false);


text:
Q: How to submit a form in a directive from some where (another method) using angularjs How to submit a form in a directive from some where (another method) using AngularJs. Here I have added my code. I need to call this export submit from different places. This form submission is the best way to to export number of records. Please give solution for this.  Thanks in advance.
App.directive('exportData',function(){
      return {
        restrict : 'AE',
        templateUrl: "ajs/views/exportData.html",
        controller: 'exportDataController'
    }
});

exportData.html

<form method=post id='export_lead' class='leadExport' action='/app/dao/test?a=bulkExport'><input type='hidden' name='ids' id='ids' value='" + JSON.stringify(ids) + "'></form>

// from controller
$scope.exportLeads = function(type, reportData)
{
    // Here I need to call form submit.
    angular.element(document.getElementById('export_lead')).triggerHandler('click');
};


text:
Q: Update Database Table with tableAdapterTable command in C# I have a C# form program in Visual Studio 2012 with built in database I'm trying to update. It's about customers and pizza orders.
I am able to add new Customers / PizzaOrders just fine, however when I try to do an update, I always get an error stateing "No overloaded method "methodName" takes 4 arguments."
Here is what I'm trying to use to update:
this.customerTableAdapter.UpdateCustomer(Name, Telephone, Original_CustomerID, CustomerID);

And here is the Visual Studio generated SQL to run this update:
UPDATE [dbo].[Customer] SET [Name] = @Name, [Telephone] = @Telephone WHERE (([CustomerID] = @Original_CustomerID) AND ([Name] = @Original_Name) AND ([Telephone] = @Original_Telephone));
SELECT CustomerID, Name, Telephone FROM Customer WHERE (CustomerID = @CustomerID)

I figure I'm not putting the right variables in the command / not the right order.
Any Suggestions?

A: The query generated by Visual Studio was making it match a column by every column in the row (Name, Telephone, and CustomerID) rather than just by matching the CustomerID.
Also make sure the data types being given to the query are of the same type that the columns have.


text:
Q: Isolating cause of 0x124 WHEA_UNCORRECTABLE_ERROR consistently at address ntoskrnl.exe+4b314c I have a Windows 7 64-bit machine that's freezing up roughly once a month.  The last five minidumps all indicate "Caused by address" ntoskrnl.exe+4b314c, and I'm trying to figure out who owns (or is triggering failed calls of) the code at that address.
Here's the !analyze -v output from the most recent mini-dump:
Microsoft (R) Windows Debugger Version 6.3.9600.17029 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

Loading Dump File [C:\Windows\Minidump\102116-50450-01.dmp]
Mini Kernel Dump File: Only registers and stack trace are available

************* Symbol Path validation summary **************
Response                         Time (ms)     Location
Deferred                                       SRV*C:\SymCache*http://msdl.microsoft.com/download/symbols
Symbol search path is: SRV*C:\SymCache*http://msdl.microsoft.com/download/symbols
Executable search path is:
Windows 7 Kernel Version 7601 (Service Pack 1) MP (12 procs) Free x64
Product: WinNt, suite: TerminalServer SingleUserTS
Built by: 7601.19160.amd64fre.win7sp1_gdr.160211-0600
Machine Name:
Kernel base = 0xfffff800`04201000 PsLoadedModuleList = 0xfffff800`04448730
Debug session time: Fri Oct 21 16:47:24.260 2016 (UTC - 7:00)
System Uptime: 0 days 0:00:25.275
Loading Kernel Symbols
.

Press ctrl-c (cdb, kd, ntsd) or ctrl-break (windbg) to abort symbol loads that take too long.
Run !sym noisy before .reload to track down problems loading symbols.

..............................................................
..........
Loading User Symbols
Mini Kernel Dump does not contain unloaded driver list
*******************************************************************************
*                                                                             *
*                        Bugcheck Analysis                                    *
*                                                                             *
*******************************************************************************

Use !analyze -v to get detailed debugging information.

BugCheck 124, {0, fffffa802d3f77c8, 0, 0}

Probably caused by : GenuineIntel

Followup: MachineOwner
---------

7: kd> !analyze -v
*******************************************************************************
*                                                                             *
*                        Bugcheck Analysis                                    *
*                                                                             *
*******************************************************************************

WHEA_UNCORRECTABLE_ERROR (124)
A fatal hardware error has occurred. Parameter 1 identifies the type of error
source that reported the error. Parameter 2 holds the address of the
WHEA_ERROR_RECORD structure that describes the error conditon.
Arguments:
Arg1: 0000000000000000, Machine Check Exception
Arg2: fffffa802d3f77c8, Address of the WHEA_ERROR_RECORD structure.
Arg3: 0000000000000000, High order 32-bits of the MCi_STATUS value.
Arg4: 0000000000000000, Low order 32-bits of the MCi_STATUS value.

Debugging Details:
------------------

BUGCHECK_STR:  0x124_GenuineIntel

CUSTOMER_CRASH_COUNT:  1

DEFAULT_BUCKET_ID:  WIN7_DRIVER_FAULT

PROCESS_NAME:  System

CURRENT_IRQL:  0

ANALYSIS_VERSION: 6.3.9600.17029 (debuggers(dbg).140219-1702) amd64fre

STACK_TEXT:
fffff880`03d1d6f0 fffff800`044c5cb9 : fffffa80`2d3f77a0 fffffa80`24f7eb50 00000000`00000029 00000000`00000000 : nt!WheapCreateLiveTriageDump+0x6c
fffff880`03d1dc10 fffff800`043a4c07 : fffffa80`2d3f77a0 fffff800`0441f2d8 fffffa80`24f7eb50 00000000`00000000 : nt!WheapCreateTriageDumpFromPreviousSession+0x49
fffff880`03d1dc40 fffff800`0430bc55 : fffff800`04481ba0 00000000`00000001 fffffa80`2d456090 fffffa80`24f7eb50 : nt!WheapProcessWorkQueueItem+0x57
fffff880`03d1dc80 fffff800`0427e065 : fffff880`01776e00 fffff800`0430bc30 fffffa80`24f7eb00 00000000`00000000 : nt!WheapWorkQueueWorkerRoutine+0x25
fffff880`03d1dcb0 fffff800`0450fc6a : 00000000`00000000 fffffa80`24f7eb50 00000000`00000080 fffffa80`24eda870 : nt!ExpWorkerThread+0x111
fffff880`03d1dd40 fffff800`04266086 : fffff880`03b31180 fffffa80`24f7eb50 fffff880`03b3c1c0 00000000`00000000 : nt!PspSystemThreadStartup+0x5a
fffff880`03d1dd80 00000000`00000000 : fffff880`03d1e000 fffff880`03d18000 fffff880`03d1d9e0 00000000`00000000 : nt!KxStartSystemThread+0x16

STACK_COMMAND:  kb

FOLLOWUP_NAME:  MachineOwner

MODULE_NAME: GenuineIntel

IMAGE_NAME:  GenuineIntel

DEBUG_FLR_IMAGE_TIMESTAMP:  0

IMAGE_VERSION:

FAILURE_BUCKET_ID:  X64_0x124_GenuineIntel_PROCESSOR_MAE_PRV

BUCKET_ID:  X64_0x124_GenuineIntel_PROCESSOR_MAE_PRV

ANALYSIS_SOURCE:  KM

FAILURE_ID_HASH_STRING:  km:x64_0x124_genuineintel_processor_mae_prv

FAILURE_ID_HASH:  {435e2195-e498-1e77-0526-f8d7450275e5}

Followup: MachineOwner

And here is the output of !errrec fffffa802d3f77c8
7: kd> !errrec fffffa802d3f77c8
===============================================================================
Common Platform Error Record @ fffffa802d3f77c8
-------------------------------------------------------------------------------
Record Id     : 01d22bf56b81ac86
Severity      : Fatal (1)
Length        : 864
Creator       : Microsoft
Notify Type   : Machine Check Exception
Timestamp     : 10/21/2016 23:47:24 (UTC)
Flags         : 0x00000002 PreviousError

===============================================================================
Section 0     : Processor Generic
-------------------------------------------------------------------------------
Descriptor    @ fffffa802d3f7848
Section       @ fffffa802d3f7920
Offset        : 344
Length        : 192
Flags         : 0x00000001 Primary
Severity      : Fatal

Proc. Type    : x86/x64
Instr. Set    : x64
Error Type    : Micro-Architectural Error
Flags         : 0x00
CPU Version   : 0x00000000000206c0
Processor ID  : 0x0000000000000000

===============================================================================
Section 1     : x86/x64 Processor Specific
-------------------------------------------------------------------------------
Descriptor    @ fffffa802d3f7890
Section       @ fffffa802d3f79e0
Offset        : 536
Length        : 64
Flags         : 0x00000000
Severity      : Fatal

Local APIC Id : 0x0000000000000000
CPU Id        : c0 06 02 00 00 08 20 00 - ff e3 9e 02 ff fb eb bf
                00 00 00 00 00 00 00 00 - 00 00 00 00 00 00 00 00
                00 00 00 00 00 00 00 00 - 00 00 00 00 00 00 00 00

===============================================================================
Section 2     : x86/x64 MCA
-------------------------------------------------------------------------------
Descriptor    @ fffffa802d3f78d8
Section       @ fffffa802d3f7a20
Offset        : 600
Length        : 264
Flags         : 0x00000000
Severity      : Fatal

Error         : Unknown (Proc 0 Bank 2)
  Status      : 0xb200000000010005

This is a whitebox machine built several years ago (with parts upgraded over time to stay current).  Periodically I make sure it still passes all the stress tests I can throw at it (Prime95, Memtest86, etc).  I tried some brief retests with no failures, and am going to rerun full cycles overnight.
I thought the freezes originally began after I installed several pieces of software (possibly including drivers) a year or two ago, but didn't have time to investigate or troubleshoot at the time.  I can't remember which software it would have been or exactly when (and to be honest, that could be unrelated or a different set of BSOD's already solved).  I did go through a while back and cull software / drivers, particularly anything that might have looked suspect or appeared in other, older BSOD's (e.g. stuff like cbfs5.sys).
I've applied the most recent BIOS updates, and the latest drivers that work properly for me.  (Some of the hardware is old, and in rare cases I found the newest drivers cause other problems).  Most Windows updates are installed (there might be some in the last couple months that haven't been applied yet - since it's a fairly critical workstation, I take a very controlled approach to updates, creating a full backup image beforehand and doing a set of regression tests after each update cycle.  As a result I'm slow to update, but generally this machine is more stable and predictable than others I maintain which are set to auto-update.  That's one reason I'm putting off Win 10 for now).
Temperatures all seem reasonable.
My system is configured to write Kernel memory dumps, but for reasons unknown to me one isn't being written when this issue occurs (it occurred earlier today but my MEMORY.DMP at that path has a modified date of nearly a month ago).
The motherboard is an Asus P6T6 WS Revolution (X58 chipset) and the CPU is a 2.4GHz Hex Core Intel Xeon E5645.  I have 48 GB of ECC RAM installed.
I don't have a ton of experiencing analyzing memory dumps, and would be grateful for any help/suggestions.

A: The fault, as hinted at in the error record, comes from the processor's Machine-Check Architecture.
Some background from MSDN's Ntdebugging blog: Interpreting a WHEA error for a MCA fault.
You can find all the gory details of MCA in Chapter 15 of the Intel Software Developer's Manual, Volume 3B.
The useful information in the dump is the last line of the error record, which is the value of the associated IA32_MCi_STATUS model-specific register. That is documented in section 15.3.2.2 of the Intel manual. Your value of 0xb200000000010005 breaks down as:

*

*Bit 63: Register valid

*Bit 61: Error uncorrected

*Bit 60: Error enabled

*Bit 57: Processor context corrupt

*Bits 31–16: Model-specific error code 1(which does not appear to be publicly documented for your processor)

*Bits 15–0: MCA error code 5(which according to Table 15‑8 in section 15.9.1 means Internal parity error)

I don't know whether all that suggests your CPU, or motherboard, or some other hardware might be faulty. It seems unlikely to be a software issue, though, because software should not be able to cause an internal hardware error like this.
You might like to try changing your dump settings from "Small memory dump" to "Kernel memory dump" and waiting for the fault to happen again; perhaps the extra information in the larger dump file will give you some additional clues to what's going on at the time of the crash.


text:
Q: Pyinstaller exe not working when I change the icon I was making a GUI with python Tkinter. It also uses numpy and matplotlib also. So, I used pyinstaller and make a exe out of the python script. It runs flawlessly and did all what i wanted.
Then I tried to change the tk icon from the gui window (i am using windows 10) with this line
master.iconbitmap(default='image.ico')

other than this line i change nothing of the main program. Then using pyinstaller and I made the exe without any error. But when I tried to run the exe it shows "Fatal Error! file.exe returned -1"
What am i missing? How to fix this problem?
Also I have an additional problem, the 1st exe i build (without changing the icon) is running on Windows-10 and Windows-8 but not in Windows-7. In windows-7 it shows the same error "Fatal Error! file.exe returned -1"

A: For those still experiencing this issue, I found that pointing the iconbitmap line to the full path will resolve the issue. I was originally having the same problem as the original poster until I entered the full path to my .ico file.
Example:
wm_iconbitmap('E:\icon_name.ico')

A: try setting datas like:
a.datas += [('C:\\Users\\KoushikNaskar\\Desktop\\Python\\image.ico', 'image.ico')]

from:
http://pythonhosted.org/PyInstaller/spec-files.html#adding-data-files
datas is a list of tuples: (source, dest)

A: Your problem (most likely) is that you are not bundling the icon's image when using pyinstaller to compile your program to a .exe.
You'll see something like this in your .spec file:
a = Analysis(['your_script.py'],
         pathex=['your_path'],
         binaries=None,
         datas=['file_1_path', ....], # Here
         hiddenimports=[],
         hookspath=[],
         runtime_hooks=[],
         excludes=[],
         win_no_prefer_redirects=False,
         win_private_assemblies=False,
         cipher=block_cipher)

Or you could do something like
a.datas += [item1, item2, ...]


text:
Q: how to validate Paramter id and token Claim Id are same from Authorize tag is there any way to validate parameter value and my token value are same or not.. from Authorize Tag
[Authorize(AuthenticationSchemes = "abc", Roles = "Parents", Policy = "ParentsOnly")]

example: public async Task<IActionResult> GetParentInfoAsync(int parentId) { }
my JWT token generated from ParentId 221   and  i pass in parameter 225 id .. its work fine parameter id compare my custom claim method... but how to authorize tag auto validate this is not a correct parentId
and if its not possible i want to get parameter value from below method.in request.Path i am getting full url.. but i want only paramter value and controller name any idea how to get this
 protected override async Task<AuthenticateResult> HandleAuthenticateAsync(){
var requestvalue = Request.Path;
}

Startup.cs
   services.AddAuthorization(options =>
                {
                    options.AddPolicy("ParentOnly", policy => policy.RequireClaim(ClaimTypes.Sid));
                });

in ClaimTypes.Sid  my ParentId


text:
Q: JAVASCRIPT: why my two flatten functions doesnt work? Im trying to implement flattern with reduce, reduce will use each:
function each(collection, iterator) {
    if (Array.isArray(collection)){
      for (var i=0;i<collection.length;i++){
        iterator(collection[i],i,collection)
      }
    }else {
      for (var key in collection){
        iterator(collection[key],key,collection)
      }
    }
  };
    function reduce(collection, iterator, accumulator) {
    var initalizing = arguments.length === 2;
    each(collection,function(value){
      if (initalizing){
        accumulator = value;
        initalizing = false;
      } else {
      accumulator = iterator(accumulator,value);
      }
    });
    return accumulator;
  };

As you can see my flatten didn't return all the elements in the array, I want to keep my if statement here but which part should I correct to make the flatten works?
  function flatten(array){
  return reduce(array,function(flat,toFlatten){
      if(Array.isArray(toFlatten)){
          return flat.concat(flatten(toFlatten));

          }else{

          return flat.concat(toFlatten);
              }
      },[]);
  };
flatten([[1,2,3],2,3,[3,4,5],5,6]); //

Also, if I don't use Flatten(toFlatten) I believe this is recursion? instead, I want to use each function to iterate the nested array...but seems like I have some syntax error and it doesn't work:
  function flatten(array){
      return reduce(array,function(flat,toFlatten){
          return each(toFlatten,function(item){
             if(Array.isArray(toFlatten)){
                 return array.push(item);
                 }
              });
              return array.push(toFlatten);
          },[]);
      };

A: The problem is this:
flattern([1,2,3],2,3,[3,4,5],5,6)

You are passing in multiple arguments, not an array.
function flattern (a){
    console.log(a);  //[1, 2, 3]
    console.log(arguments);  //[Array[3], 2, 3, Array[3], 5, 6]
}

You would need to pass in
flattern([[1,2,3],2,3,[3,4,5],5,6]);


text:
Q: image object crop and draw in center of canvas How can I crop an image and then draw it in the center of a canvas?
Currently I have a drop div where I can drop an image on, which is then picked up by JavaScript. I then want JavaScript to check what is higher (height or width). If the height is highest I want it to be 200px and the width to be adjusted to the aspect ratio. After that I want JavaScript to draw the image in the canvas where the center of the image is the center of the canvas.
The current code I have, which isn't working (I'm not sure why):
(for simplicity, I just passed an image from the web to the function)
render('http://www.aboveandbeyond.nu/sites/www.aboveandbeyond.nu/files/news/europe_above_beyond_tour.jpg');

function render(src){

var image = new Image();
var canvas = document.getElementById("artworkcanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
image.onload = function(){

    var sourceX = 200;
    var sourceY = 0;
    var sourceWidth = 200;
    var sourceHeight = 200;
    var destWidth = sourceWidth;
    var destHeight = sourceHeight;
    var destX = canvas.width / 2 - destWidth / 2;
    var destX = 0;
    var destY = canvas.height / 2 - destHeight / 2;
    var destY = 0;
    var MAX_WIDTH = 200;
    var MAX_HEIGHT = 200;

    if (image.height == image.width) {
        image.width = MAX_WIDTH;
        image.height = MAX_HEIGHT;
    } else {
        if(image.height < image.width) {
            console.log("height smaller");
            image.width *= MAX_HEIGHT / image.height;
            image.height = MAX_HEIGHT;
        } else {
            image.height *= MAX_WIDTH / image.width;
            image.width = MAX_WIDTH;
        }
    }

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    canvas.width = image.width;
    canvas.height = image.height;

    ctx.drawImage(image, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
};

image.src = src;

}

A: Here's one way to use the scaling version of drawImage while maintaining aspect ratio:
  // calc scale that fits into 200x200 and also maintains aspect ratio
  var scale=Math.min((MAX_WIDTH/img.width),(MAX_HEIGHT/img.height));

  ctx.drawImage(img,
            0,0,img.width,img.height,
            (canvas.width-img.width*scale)/2, (canvas.height-img.height*scale)/2,
                img.width*scale, img.height*scale
           );

Example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var img=new Image();
img.onload=start;
img.src="http://www.aboveandbeyond.nu/sites/www.aboveandbeyond.nu/files/news/europe_above_beyond_tour.jpg";
function start(){

  var MAX_WIDTH = 200;
  var MAX_HEIGHT = 200;
  var iw=img.width;
  var ih=img.height;

  // calc scale that fits into 200x200 and also maintains aspect ratio
  var scale=Math.min((MAX_WIDTH/iw),(MAX_HEIGHT/ih));
  var sw=iw*scale;
  var sh=ih*scale;

  ctx.drawImage(img,
                0,0,iw,ih,
                (canvas.width-sw)/2,(canvas.height-sh)/2,iw*scale,ih*scale
               );

}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>


text:
Q: Encode between Objective-C and swift, does not match My application's network request is encoded.
In Objective-C
NSData *encodeData = [str dataUsingEncoding:NSUTF8StringEncoding];
dataStr = [encodeData base64EncodedStringWithOptions:0];

I want to transform it to swift.
Here is the swift code:
let dataEncodeTemp = dataTempStr.data(using: String.Encoding.utf8)
let dataStr = dataEncodeTemp?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))

I think , the result should be the same. But it does not.
The Objective-C data:
(lldb) po str// initial
{"userType":2,"password":"qazwsx2","account":"15921810000"}

(lldb) po dataStr // encoded
eyJ1c2VyVHlwZSI6MiwicGFzc3dvcmQiOiJxYXp3c3gyIiwiYWNjb3VudCI6IjE1OTIxODE3MDUzIn0=

The swift data:
po dataTempStr // initial
"{\"userType\":2,\"account\":\"15921810000\",\"password\":\"qazwsx2\"}"

(lldb) po dataStr

▿ Optional<String> // encoded
  - some : "eyJ1c2VyVHlwZSI6MiwiYWNjb3VudCI6IjE1OTIxODE3MDUzIiwicGFzc3dvcmQiOiJxYXp3c3gyIn0="

I want to know why , and solve it.
I shall try the bridge.
Any good solution?

A: Those aren't ever going to match, seeing as the two strings have JSON keys in differing orders; one is userType, password, account; the other is userType, account, password.


text:
Q: Type guard for array element's "possibly undefined" error TSC gives an error which is added as a comment in to code.
tsconfig: "noUncheckedIndexedAccess": true
type Tfactors = [number, number, number, number];

export default function changeEnough(pocket: Tfactors, bill: number): boolean {
  const coinToDolarFactors: Tfactors = [0.25, 0.1, 0.5, 0.01];
  let pocketTotal = 0;

  for (let i in pocket) {

    if (pocket[i] !== undefined && coinToDolarFactors[i] !== undefined) {
      //Object is possibly 'undefined'.ts(2532)
      pocketTotal += pocket[i] * coinToDolarFactors[i];
    }
  }

  return pocketTotal >= bill;
}

I solved this problem like this:
type Tfactors = [number, number, number, number];

export default function changeEnough(pocket: Tfactors, bill: number): boolean {
  const coinToDolarFactors: Tfactors = [0.25, 0.1, 0.5, 0.01];
  let pocketTotal = 0;

  for (let i in pocket) {
    const pocketValue = pocket[i];
    const factor = coinToDolarFactors[i];
    if (pocketValue !== undefined && factor !== undefined) {
      pocketTotal += pocketValue * factor;
    }
  }

  return pocketTotal >= bill;
}

I am new on TypeScript and I do not know is this optimal way to solve this problem. Can I solve this problem without declaring pocketValue  and factor variables and without use ! to mute TSC.

A: If you do not want to use ! to mute TSC or assign array elements to new variables, you can explicitly type array index, i.e.
type Tfactors = [number, number, number, number];

export default function changeEnough(pocket: Tfactors, bill: number): boolean {
  const coinToDolarFactors: Tfactors = [0.25, 0.1, 0.5, 0.01];
  let pocketTotal = 0;

  for (let _i in pocket) {
    /* --  type it explicitly here -- */
    let i = _i as Exclude<keyof Tfactors, keyof []>;
    // *if* check is not required if you are confident they are defined at runtime
    if (pocket[i] !== undefined && coinToDolarFactors[i] !== undefined) {
      //Object is possibly 'undefined'.ts(2532)
      pocketTotal += pocket[i] * coinToDolarFactors[i];
    }
  }

  return pocketTotal >= bill;
}

A: From the doc Pedantic Index Signature Checks (--noUncheckedIndexedAccess), we know

One consequence of using --noUncheckedIndexedAccess is that indexing into an array is also more strictly checked, even in a bounds-checked loop.

Under this new mode, every property access (like foo.bar) or indexed access (like foo["bar"]) is considered potentially undefined.

solution:
If you need to access that property, you'll either have to check for its existence first or use a non-null assertion operator (the postfix ! character).
// Checking if it's really there first.
const pocketValue = pocket[i];
const factor = coinToDolarFactors[i];
if (pocketValue !== undefined && factor !== undefined) {
  pocketTotal += pocketValue * factor;
}

// Basically saying "trust me I know what I'm doing"
// with the '!' non-null assertion operator.
pocketTotal += pocket[i]! * coinToDolarFactors[i]!;

A:
Can I solve this problem without declaring pocketValue and factor variables [or] without use ! to mute TSC.

No, you cannot, unfortunately.


text:
Q: How to tell where a Scala project "starts"? I'm moving to Scala from a Python background, and am getting kind of overwhelmed with the fact that everything is an object. I'm having trouble tracing where the execution of the project begins.
What are some methods for finding where a Scala project's controlling logic begins?

A: If you're using sbt, you can:
show discoveredMainClasses

and it will show you all the entry points:

*

*(Scala 2 and 3) all the objects with main methods, including those that get a main by doing extends App

*(Scala 3 only) all the methods annotated @main
run will bring up a menu asking you to choose an entry point, if more than one is found within a project.
That said, some frameworks use their own entry points that aren't necessarily main methods. In those cases, there are only framework-specific answers.


text:
Q: Go to top frame in pdb (python debugger) When pdb / ipdb is used in post-mortem mode, it drops you into an interactive shell where you can explore the environment at the stack frame of the most deeply nested code. I'm usually not interested in the the situation several levels down into some library -- I'm interested in my function because that's what really caused the problem. So, most of the time I have to press "u" several times to get back up to the level of the code I wrote.
Is there a way I can jump to the "top" to speed this up? Or even better, a shortcut to go straight to a particular stack frame?
(By the way, the stack feels a little "upside down" to me here. A function that calls another function puts the new call on the top of the stack, right? So I feel like the pdb u(p) command is actually moving you down into the stack...)

A: You could do "up n" with an arbitrarily high value for n, like 99:
https://docs.python.org/3/library/pdb.html#pdbcommand-up
PS. It was mentioned by Chris in a comment on the OP.
I do re-post it as an answer to make it more visible, and with a link to the documentation.

A: You can use a PdbExtension for this.
See https://github.com/fschulze/pytest-pdb/pull/5 where this is about to be added to pytest-pdb.


text:
Q: parametrized query in excel 2010 cell i would like to make a formula in excel that querys my microsoft sql server 2005 database
something like:
= select count(*) as 'aantal bezoeknummers'
from bezwe
where z03 between A2 and B2
and z02 = C1;
the bold referers should be the parameters given in the excel file
my previous tries:
i went to: data>from other sources>from MS query>MS access database.
after a long search to the location of my database on the server i found out that the extension is .MDF
the MS query tool only works with .MDB and .ACCDB
other searches on the net or on this forum didn't helped me out with a proper understandable solution
if there is any solution possible i would be please with your help

A: You will need to add the query via Import from Other Sources, MS SQL Server. In the query, enter ? for each parameter you want to take from a cell. Excel should then automatically ask for the parameters, and you can link to your cells. See http://snippetsandhelp.blogspot.de/2013/05/excel-2013-getting-data-from.html?m=1 or one of the various articles when searching for "excel query parameters".


text:
Q: How can I join tables with different data types using Entity Framework With the situation of using Entity Framework,I want to join tables with two field in same value,but the fields are identified with different data types. For example,there is a field which the data type is 'Guid',but in another table the associated field is 'string' type. I am confused to achieve the goal. Can somebody give me some ideas.Here are my codes, emps.EmpGuid is a 'Guid' data type and flowCode.Object is a string:
DbSet<tb_Emp_Manager_Zbdl> dbEmp = zbdlcontext.Emp_Manager;
DbSet<Tb_Corp_CompanyInfo_Zbdl> dbCompany = zbdlcontext.Corp_CompanyInfos;
DbSet<Tb_FlowCode_Zbdl> dbFlowCode = zbdlcontext.FlowCodes;
DbSet<Tb_Emp_Post_Zbdl> dbEmpPost = zbdlcontext.Emp_Post;
var query = from emps in dbEmp
            join companies in dbCompany on emps.CorpGuid equals companies.CorpUserGuid
            join flowCode in dbFlowCode on new { EmpGuid = emps.EmpGuid.ToString(), AreaCode = areaCode } equals new { EmpGuid = flowCode.ObjectId, AreaCode = flowCode.AreaCode } into jFlowCodes
            from flowCodes in jFlowCodes.DefaultIfEmpty()
            join post in dbEmpPost on emps.EmpGuid equals post.EmpGuid into jPosts
            from posts in jPosts.DefaultIfEmpty()
            select new tb_Emp_Manager()
                       {
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            FlowCode = flowCodes.FlowCode,
                            corpName = companies.CorpName
                       };


text: Q: How do I keep a VBScript Message Box Centered? I'm starting to learn VBScript but what I can't find is a tutorial on how to make a message box centered. I want to make the message box centered even if the person opening the file tries to move it. I hope someone replies! Thanks.


text:
Q: change temp dir for Neo4j-OGM unit tests? Out of the box, the junit tests of the Neo4j-OGM library create the temporary database files under /tmp.
How can I change this?
Setting java.io.tmpdir in the maven-surefire-plugin config does not seem to do the trick.
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <java.io.tmpdir>/alt/tmp</java.io.tmpdir>
  </configuration>
</plugin>

A: This worked for me
<plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-surefire-plugin</artifactId>
     <configuration>
           <systemProperties>
               <property>
                   <name>java.io.tmpdir</name>
                   <value>/path/to/temp</value>
                </property>
           </systemProperties>
     </configuration>
...
</plugin>

Update since the syntax above is deprecated:
<plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
         <configuration>
               <systemPropertyVariables>
                  <java.io.tmpdir>/path/to/temp</java.io.tmpdir>
               </systemPropertyVariables>
         </configuration>
    ...
    </plugin>


text:
Q: Gmail Contextual Gadget API: Is there a way to access the RFC 822 Message ID? is there a way to access the RFC 822 Message ID from within a Contextual Gadget?
According to https://developers.google.com/gmail/contextual_gadgets?hl=de#supported_scopes only the Google Message ID can be accessed.
However, I don't understand this restriction, as the Google Message ID is also accessible...
Best regards,
Joe

A: No not directly, but you can if you use some java there is a api which can solve your problem.
you can find it here
https://code.google.com/p/java-gmail-imap/
MY CODE:
IMAPFolder folder = (IMAPFolder) store.getFolder("[Gmail]/All Mail");

        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(IMAPFolder.FetchProfileItem.X_GM_THRID);
        fp.add(IMAPFolder.FetchProfileItem.X_GM_MSGID);

        if (folder != null) {
            folder.open(Folder.READ_ONLY);
            folder.fetch(folder.getMessages(), fp);

            GmailMessageIDTerm messageID_term = new GmailMessageIDTerm(Long.parseLong(msgId, 16)+"");
            com.google.code.javax.mail.Message[] messageID_Meassages = folder.search(messageID_term);

            if(messageID_Meassages.length > 0){

                IMAPMessage main_Meassage = (IMAPMessage)messageID_Meassages[0];
                GmailThreadIDTerm thread_term = new GmailThreadIDTerm(main_Meassage.getGoogleMessageId() + "");
                com.google.code.javax.mail.Message[] thread_Messages = folder.search(thread_term);

                for(com.google.code.javax.mail.Message m: thread_Messages){
                    IMAPMessage imapMessage = (IMAPMessage)m;
                    // here is your every message of current thread

                }

            }
        }


text:
Q: "The application bundle does not contain a valid identifier" error after installing socket mobile scan api sdk After installing Socket Mobile Scan Api Sdk via cocoa pod, I couldn't run on real device anymore. I noticed the sdk include "Resources" group. But I couldn't able to run the project on real device even after renaming and deleting the "Resources" group. I'm using "scanapisdk-10-3-41 2" on Xcode 7.3.1 and trying to run on ipad Air 2.

A: I'm posting the answer just in case if other people face the same problem in the future. As I commented in the original question. This issue is solved by removing space in the project target name
(eg. Sample Project -> SampleProject).
I'm not sure about what is the real reason causing the problem. However I don't face anymore issue after I re-name my project target.
Edit : I faced the problem again after installing another frameworks using cocoapods. But I managed to solve the problem with a workaround (re-naming target).


text:
Q: How to initialise Firestore query in initState in flutter I am trying to load the data from Firestore, with the help of streambuilder i am getting the respective data and displaying it to the user.
I am passing the value to a variable called 'total' and this total is inialised with 0 and when i try to show this total value it first should the default(0) value and the it takes the value from Firestore.
Below you can see the code
            StreamBuilder<DocumentSnapshot>(
                stream: FirebaseFirestore.instance.collection('UserData').doc(getUid()).snapshots(),
                builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
                  if (!snapshot.hasData) return const Text("Loading...");
                  final DocumentSnapshot? document = snapshot.data;
                  final Map<String, dynamic> documentData = document?.data() as Map<String, dynamic>;

                  accountList = (documentData['accounts'] as List).map((accountList) => accountList as Map<String, dynamic>).toList();
                  // getTotalFund(accountList);
                  List amountData=[];
                  double convertAmount;

                  for(int i=0; i<accountList.length;i++){
                    if(accountList[i]['accountType'] == 'Savings' || accountList[i]['accountType'] == 'Cash' ){
                      amountData.add(double.parse(accountList[i]['amountBalance'].replaceAll(',','')));
                    }
                  }
                  convertAmount = amountData.reduce((value, element) => value + element);
                  totalFund = amountFormat.format(convertAmount);

                  return Text(
                    documentData['name'],
                    style: const TextStyle(
                      fontSize: 16,
                      fontFamily: "Gilroy SemiBold",
                    ),
                  );
                }),

the value total amount i am getting in the Text widget.
Text('\u{20B9} ', style: TextStyle(color: Color(0xff9c9c9c), fontFamily: "Gilroy Medium", fontSize: 23)),
Text(totalFund.toString(),style: const TextStyle(color: Colors.black, fontFamily: "Gilroy Bold", fontSize: 35)),

how to load the totalFund in initState so it will not show the null value.

A: try this:
 Future<DocumentSnapshot> getDoc() async {
    return await FirebaseFirestore.instance.collection('UserData').doc(getUid());
 }

then set FutureBuilder as parent of your body widget like this:
FutureBuilder(future: getDoc(),
       builder: (context, snapshot){
            if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Text("Loading...");
                } else {
                  if (snapshot.hasError) {
                    return const Text("error");
                  } else {
                    final DocumentSnapshot? document = snapshot.data;
                    final Map<String, dynamic> documentData =
                        document?.data() as Map<String, dynamic>;

                    accountList = (documentData['accounts'] as List)
                        .map((accountList) => accountList as Map<String, dynamic>)
                        .toList();
                    // getTotalFund(accountList);
                    List amountData = [];
                    double convertAmount;

                    for (int i = 0; i < accountList.length; i++) {
                      if (accountList[i]['accountType'] == 'Savings' ||
                          accountList[i]['accountType'] == 'Cash') {
                        amountData.add(double.parse(
                            accountList[i]['amountBalance'].replaceAll(',', '')));
                      }
                    }
                    convertAmount =
                        amountData.reduce((value, element) => value + element);
                    totalFund = amountFormat.format(convertAmount);

                    return yourBodyWidget;
                  }
          })


text:
Q: facebook friends invitation dialog embedded in the page How can i get facebook friends invitation dialog embedded my page?
i.e. http://apps.facebook.com/promotionshq/contests/96234/invites/new
unlike other dialog boxes it should open in the same window.
How it can be done using Javascript SDK?

A: You can include a "display" parameter for any dialog to indicate the type you want. But Facebook will always use a separate window if it decides it is "insecure". You can provide an access token, or have the user already authenticated to display inline.
"iframe: Display the dialog in a lightbox iframe on the current page. Because of the risk of clickjacking, this is only allowed for some certain dialogs, and requires you to pass a valid access_token."
https://developers.facebook.com/docs/reference/dialogs/


text:
Q: Finding Expected Value : Escaping Prisoner Question Question: Prisoner locked in a cell with $n$ doors. Only one door leads to freedom, and all the other doors lead to a dungeon where the prisoner is forced to stay $a_{i} $ days for $i=2,....n$ when $i$ is the selected door (the first door can be set as the door that leads to freedom, so that $a_{1}=0$). The prisoner chooses a random door with equal probability to all doors and passes through it. If he did not choose the door that leads to freedom, after staying in the dungeon $i$ (when $i \neq 1$) he returns to the cell and picks again a random door. Suppose the prisoner does not remember which doors he has already checked. Let $X$ be the number of days till the prisoner gets to freedom:
A. Calculate $E[x]$.
B. Calculate $Var(x)$.
My Solution: For A:
I know that:
$E[X]=E[X|Y=i]=\sum_{i=2}^{n}E[X|Y=i]\cdot P(Y=i)$
$E[X]=\sum_{i=2}^{n} (E[x]+a_{i})\cdot \frac{1}{n-1} $
$E[X]=\frac{E[X]}{n-1}\sum_{i=2}^{n} a_{i} $
$E[X]=\frac{E[X]}{n-1}\cdot (\frac{n-1}{2}\cdot (a_{2}+a_{n})) $
 But how can I find the expected value from here?

A: You've made some mistakes.
The equation $E[X]=E[X|Y=i]$ is meaningless, since $i$ is not defined.  $i$ is a dummy variable in the summation, and and has no meaning outside it.  This isn't so important, as it happens, because the next expression is correct, but you don't want to write this.
The equation $$E[X]=\sum_{i=2}^{n} (E[x]+a_{i})\cdot \frac{1}{n-1}$$ is wrong.  $\Pr(Y=i)=\frac1n$, not $\frac1{n-1}.$  It's okay to ignore the case $i=1$ in the sum, since the prisoner escapes immediately, but that doesn't change the probabilities.
The third equation is also wrong, even if we ignore the mistake in the second one.  From $$E[X]=\sum_{i=2}^{n} (E[x]+a_{i})\cdot \frac{1}{n-1},$$ you should get $$E[X] = \frac1{n-1}\sum_{i=2}^nE[X] + \frac1{n-1}\sum_{i=2}^n a_i=E[X]+\frac1{n-1}\sum_{i=2}^n a_i$$
In the fourth equation, you seem to be assuming that the $a_i$ form an arithmetic progression, but this is not given in the problem.  There is no way to simplify the sum of the $a_i$.
Try it again.


text:
Q: Cassandra read queries return empty results Using springframework data cassandra When I execute Cassandra read queries it always returns empty results But records are present in cassandra table.
I'm facing this problem when delete action occurred on the same partition.
For Example :
Partition A contains 1 M records and earlier I have deleted 900K records on the same partition A.
Later I couldn't get the remaining 100K records on the same partitions. Sometimes throws ReadTimeoutException or returns empty results.
This is happening when querying using springframework data cassandra. I can execute the same query and get results in a cassandra tool (Datastax or Dbeaver).
Can you please help me out with this?

A: Cassandra does not delete the data immediately, it marks to delete and will delete after configured time. In the meantime your queries can take longer. If you need the data to be deleted more quickly you need to run compact:
./nodetool compact <ks_name> <cf_name>

In any case Databases in Production require to be compacted to be in good shape.
Querying 100K rows from Spring-boot will be expensive in time, in terms of amount of information transferred through available bandwidth, and in terms of memory used. Can you post details of your configuration and check if the Spring-boot microservice Server is running out of memory and swapping during the query?.
free -h

More things. Can you check which node are you querying from Spring-boot?.
Can you paste here the CQL sent by Spring-boot?.
From cqlsh are you querying for the Data on that node/partition or for all the 100K rows?.
Are you using a Load Balancer, or proxy service or any other Service like Consul in your Spring-boot project?.
To solve the networking problems, ssh to the cassandra node you are expecting to query and check with tcpdump that effectively it is getting a connection from the computer you run your microservice.
Assuming the machine with spring-boot is 10.0.10.100, ssh to the Cassandra node you believe is receiving the connections and execute:
sudo tcpdump | grep "10.0.10.100"

Now attempt to run the queries from Spring-boot.
Open iftop in the Spring-boot Server and see what is the bandwidth consumed fetching from Cassandra.
iftop

Hope that helps. Please provide more info.
Cheers


text:
Q: Removing header  in redirected sites I am facing an issue with mobile version of my site. The site is hosted on a different domain.
I Tracked down the issue and saw that its being caused by the  being wrapped on top of my actual html code.
Here is a snippet:
<html>
    <head>
    <title>Where are you</title>
    <meta name="robots" content="noindex, nofollow">
    <meta name="description" content="Let's your friends and family know about your where about.">
    <meta name="keywords" content="Stay connected, Plan meetup, Unreachable friend, Share location, Share photos">
    </head>
    <frameset rows="100%">
        <frameset cols="100%">
            <frame src="http://wru.buttur.com" frameborder="0">
            #document
        </frameset>
    </frameset>
</html>

My website is getting loaded inside "#document".
Can i do some configuration on my domain to prevent this from happening.

A: I know this is old, but I am responding because we had a similar problem where some outside entity managed a website, and we took over after it became broken.
It was a wordpress site and everything was being wrapped inside a frameset. We were baffled by the fact that direct browser requests to hosted javascript files would work fine, but within the page it would become wrapped in frames in the network response.
Even direct jQuery.getScript() calls from external sites would exhibit the scenario. Again, worked fine if typed into browser url bar.
Turns out there's something called DNS frame forwarding.
Here's a topic that covers the scenario:
https://stackoverflow.com/questions/7083391/godaddy-dns-forward-to-ip-adds-frames-to-html
Edit:
Looks like a moderator removed that post. How strange!!  Too bad as well, that post had exactly the right answer with exactly the right description.
Well basically anyone coming across this, just research DNS frame forwarding. You'll find your answer there.
Terms for google:
website wrapped in frameset
javascript responds in frame
css in frame
Resource interpreted as Stylesheet but transferred with MIME type text/html
Uncaught SyntaxError: Unexpected token <


text:
Q: Get featured event using EventBrite API How can I show Featured event by organization using Eventbrite API in PHP ?
I have checked http://developer.eventbrite.com/doc/users/user_list_events/ .Here in status parameter I can send live status for live events , but if there is more that one Event then any how  can I identify Featured Event out of so many events?

A: That is currently not possible via the API.  If you're working with your own account, you can take the event id of your featured event and use the event_get API:
http://developer.eventbrite.com/doc/events/event_get/