text:
Q: java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing While running junit test in eclipse I am getting this Exception:
java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

I've added junit.jar library file.
I've tried different versions of junit.jar: 4.4, 4.8, etc.
How do I fix this Exception?

A: According to the JUnit GitHub team website (https://github.com/junit-team/junit/wiki/Download-and-Install), junit.jar and hamcrest-core.jar are both needed in the classpath when using JUnit 4.11.
Here is the Maven dependency block for including junit and hamcrest.
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.1.2</version>
    <scope>test</scope>
</dependency>
<!-- Needed by junit -->
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

A: You need junit-dep.jar because the junit.jar has a copy of old Hamcrest classes.

A: Just in case there's anyone here using netbeans and has the same problem, all you have to do is

*

*Right click on TestLibraries

*Click on Add Library

*Select JUnit and click add library

*Repeat the process but this time click on Hamcrest and the click add library

This should solve the problem

A: This problem is because of your classpath miss hamcrest-core-1.3.jar. To resolve this add hamcrest-core-1.3.jar as you add junit-4.XX.jar into your classpath.
At first, I encounter this problem too, but after I refer to the official site and add hamcrest-core-1.3.jar into classpath with command line, it works properly finally.
javac -d ../../../../bin/ -cp ~/libs/junit-4.12.jar:/home/limxtop/projects/algorithms/bin  MaxHeapTest.java

java -cp ../../../../bin/:/home/limxtop/libs/junit-4.12.jar:/home/limxtop/libs/hamcrest-core-1.3.jar org.junit.runner.JUnitCore com.limxtop.heap.MaxHeapTest

A: You need to add the hamcrest-core JAR to the classpath as described here: https://github.com/junit-team/junit4/wiki/Download-and-Install

A: A few steps you have to follow:

*

*Right click on the project.

*Choose Build Path Then from its menu choose Add Libraries.

*Choose JUnit then click Next.

*Choose JUnit4 then Finish.

A: As a general rule, always make sure hamcrest is before any other testing libraries on the classpath, as many such libraries include hamcrest classes and may therefore conflict with the hamcrest version you're using. This will resolve most problems of the type you're describing.

A: the simplest way of solving the problem to begin with is copying latest version of    hamcrest-code.jar     into your CLASSPATH that is the file you store other .jar files needed for compilation and running of your application.
that could be e.g.: C:/ant/lib

A: Works for me: IntelliJ IDEA 13.1.1, JUnit4, Java 6
I changed the file in project path: [PROJECT_NAME].iml
Replaced:
  <library>
    <CLASSES>
      <root url="jar://$APPLICATION_HOME_DIR$/lib/junit-4.11.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>

By:
  <library name="JUnit4">
    <CLASSES>
      <root url="jar://$APPLICATION_HOME_DIR$/lib/junit-4.11.jar!/" />
      <root url="jar://$APPLICATION_HOME_DIR$/lib/hamcrest-core-1.3.jar!/" />
      <root url="jar://$APPLICATION_HOME_DIR$/lib/hamcrest-library-1.3.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>

So the final .iml file is:
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="module-library">
      <library name="JUnit4">
        <CLASSES>
          <root url="jar://$APPLICATION_HOME_DIR$/lib/junit-4.11.jar!/" />
          <root url="jar://$APPLICATION_HOME_DIR$/lib/hamcrest-core-1.3.jar!/" />
          <root url="jar://$APPLICATION_HOME_DIR$/lib/hamcrest-library-1.3.jar!/" />
        </CLASSES>
        <JAVADOC />
        <SOURCES />
      </library>
    </orderEntry>
  </component>
</module>

P.S.: save the file and don't let to IntelliJ Idea reload it. Just once.

A: Add hamcrest-all-X.X.jar to your classpath.
Latest version as of Feb 2015 is 1.3:
http://code.google.com/p/hamcrest/downloads/detail?name=hamcrest-all-1.3.jar&can=2&q=

A: It sounds like a classpath issue, so there are a few different ways to go about it. Where does org/hamcret/SelfDescribing come from? Is that your class or in a different jar?
Try going to your project Build Path and on the Libraries tab, add a Library. You should be able to choose JUnit to your project. This is a little bit different than just having the JUnit jar file In your project.
In your Run Configuration for the JUnit test, check the Classpath. You could probably fix this by adding making sure your Classpath can see that SelfDescribing class there. The Run option in Eclipse has a different set of options for the JUnit options.

A: If this problem arise in a RCP project it can be because JUnit has been explicitly imported.
Check the editor for your plugin.xml under Dependencies tab, remove the org.junit from the Imported Packages and add org.junit to the Required Plug-ins.

A: The problem is when you set up eclipse to point to JRE instead of JDK. JRE has junit4.jar in the lib/ext folder, but not hamcrest.jar :) So the solution is to check installed JREs in Eclipse, remove the existing one and create a new one pointing to your JDK.

A: This happens when you run Ant via command line. The implicit user dependencies are added in the classpath at the end and take precedence over the project-added classpath. Run Ant with -nouserlib flag. The implicit dependencies would be excluded from the classpath.

A: There is a better answer to solve this problem.
add dependency
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

A: The hamcrest-core-1.3.jar available on maven repository is deprecated.
Download working hamcrest-core-1.3.jar from official Junit4 github link .
If you want to download from maven repository, use latest hamcrest-XX.jar.
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.2</version>
    <scope>test</scope>
</dependency>

A: I had the same problem, the solution is to add in build path/plugin the jar org.hamcrest.core_1xx, you can find it in eclipse/plugins.

A: A few steps you have to follow:

*

*Right click on the project.

*Choose Build Path & then from its menu choose Add Libraries.

*Choose JUnit then click Next.

*Choose JUnit4 then Finish.

This works for me...

A: "java.lang.SecurityException: class" org.hamcrest.Matchers "'s signer information does not match signer information of other classes in the same package"
Do it:
Right-click on your package
click on Build Path -> Configure Build Path
Click on the Libraries tab
Remove JUnit
Apply and close
Ready.

A: Try adding the jar files manually or try with force update with the latest hamcrest.jar


text:
Q: Extract Part of Title Tag Does anyone know how to extract part of the title tag using Javascript? Like, extract all text in the title tag up to a dash character, and not text after the dash character.
Example
<title>Extract this text-But not text after the dash</title>

A: Try this:
document.title.split('-')[0]

A: var title = document.title;
var dashIdx = title.indexOf("-");
var part = title.substring(0, dashIdx);

A: document.title.substring(0, document.title.indexOf('-'))

A: var dTt = document.title;
dTt.substring(0, dTt.indexOf('-'));

reference: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#Methods

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the data of dictionaries inside a dictionary using map function? This is the sample data for which I'm trying to get the value:
InvoiceAccuracy: {
data: {
  accurate: {
    invoices: 52,
    name: "1"
  },
  corrected: {
    invoices: 10,
    name: "1"
  },
  inaccurate: {
    invoices: 20,
    name: "1"
  }
},
success: true

}
Using this function(Tried):
const chartData = InvoiceGenerationData.InvoiceAccuracy.data.map(
    value => ({
      label: value.name,
      value: value.invoices
    })
  );

I have found the way to get the dictionary data. Here is the solution:
 const chartData = Object.keys(
    InvoiceGenerationData.InvoiceAccuracy.data
  ).map(key => {
    return {
      label: key,
      value: InvoiceGenerationData.InvoiceAccuracy.data[key].invoices
    };
  });


text:
Q: How to access multiple USB Type B storage devices at once? I have multiple devices with USB Type B ports for exporting data.
I am told that it is a 1:1 device. I would like to plug in 1 computer to read the data from 1 device. I am looking for a way that I could 'network' them so I can read them all from one computer. Has anyone done this, have any ideas on how I might do this?

A: You didnt provide much detail in your question, so its hard to understand exactly what you are talking about.
But if the devices are standard USB devices, all you need is a USB hub like this.  You can buy one with more ports, or daisy chain them.  Plug the hub into your computer and your devices into the hub.  If your devices draw a lot of power, you might need a powered hub like this.
If necessary, purchase USB A to B cables.

A:
I am told that it is a 1:1 device.

Who told it to you?
He probably meant that with one USB cable you can connect only one device to only one computer.
But nothing prevent you to use different USB ports to connect to multiple devices, or to use USB hub similarly.

A: Are you trying to access the data from your device after it has been exported? A simple network share would do.

*

*Select a machine that will hold the files the other machines will access.

*Create a shared folder with public access on the local network.

*Export the data to the shared folder

*Open the share folder on the other computers

The files are now available to anyone on your local network.
Note: Allowing public access is a bit of a security issue. Anyone that connects to your local network will be able to see the files and edit/delete them.


text:
Q: The app does not keep shapes when I put it in full screen I'm working on a kivy app. And I want to keep shapes once I put the app in fullscreen. When I launch the app, the screen is in mobile format. But when I put it in fullscreen, the taskbar shifts to the left and the text wallpaper and buttons don't stretch. Here is my python file:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.core.window import Window

Window.size=(480,720)
class MainInterface(Widget):
    def A_pressing(self, s_img, SM):
        if(SM.current=="background_2" or SM.current=="background_3" or SM.current=="background_4"):
            SM.transition.direction= "right"
        SM.current="background_1"
    def PRD_pressing(self, s_img, SM):
        if (SM.current == "background_3" or SM.current=="background_4"):
            SM.transition.direction = "right"
        if (SM.current == "background_1"):
            SM.transition.direction = "left"
        SM.current = "background_2"
    def SI_pressing(self, s_img, SM):
        if (SM.current == "background_4"):
            SM.transition.direction = "right"
        if (SM.current == "background_1" or SM.current == "background_2"):
            SM.transition.direction = "left"
        SM.current = "background_3"
    def SO_pressing(self, s_img, SM):
        if (SM.current == "background_1" or SM.current == "background_2" or SM.current == "background_3"):
            SM.transition.direction = "left"
        SM.current = "background_4"

class CustomApp(App):
    def build(self):
        sm = Builder.load_file("main.kv")
        return sm

CustomApp().run()

And here is my kivy language file:
#:import utils kivy.utils
MainInterface:
<MainInterface>:
    ScreenManager:
        id: sm
        size: dp(root.width), dp(root.height)
        Screen:
            name: "background_1"
            Image:
                source: ".\control_bar_images\Background_1.png"
            BoxLayout:
                pos: dp(5), dp(71)
                size_hint: (1, .70)
                padding: 18
                opacity: 0.8
                canvas:
                    Color:
                        rgb: utils.get_color_from_hex('#BDBDBD')
                    Rectangle:
                        pos: dp(0), dp(70)
                        size: self.size
                orientation: 'horizontal'
                ScrollView:
                    # take half of parents size
                    size_hint: .5, 1
                    pos: dp(0), dp(-20)
                    Label:
                        canvas.before:
                            Color:
                                rgba: 1, 1, 1, 0
                            Rectangle:
                                size: self.size
                                pos: dp(0), dp(-20)
                        markup: True
                        halign: "justify"
                        text: """[size=19]Lorem Ipsum[/size]\n\n[size=14]Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...[/size]\n\n[size=18]Lorem[/size]\n\n[size=16]Lorem ipsum dolor sit amet[/size]\n\n[size=14]Lorem ipsum dolor sit amet[/size]"""
                        color: utils.get_color_from_hex('#FFFFFF')
                        pos: dp(0), dp(-20)
                        size_hint: 1, None
                        text_size: self.width, None
                        height: self.texture_size[1]
    Image:
        source: ".\control_bar_images\Top_Bar_4.png"
        size: 480, 135
        pos: 0, root.height-135
    Button:
        size: 112.5, 75
        pos: root.width/2-205.75, root.height-100
        background_color: 1, 1, 1, 0
        on_press: root.A_pressing(A_img, sm)
        Image:
            id: A_img
            size: 112.5, 75
            source: ".\control_bar_images\image_about.png"
            center_x: self.parent.center_x
            center_y: self.parent.center_y
    Button:
        size: 112.5, 75
        pos: root.width/2-110.25, root.height-100
        background_color: 1, 1, 1, 0
        on_press: root.PRD_pressing(PRD_img, sm)
        Image:
            id: PRD_img
            size: 112.5, 75
            source: ".\control_bar_images\Likes_Btn.png"
            center_x: self.parent.center_x
            center_y: self.parent.center_y
    Button:
        size: 112.5, 75
        pos: root.width/2-12.75, root.height-100
        background_color: 1, 1, 1, 0
        on_press: root.SI_pressing(SI_img, sm)
        Image:
            id: SI_img
            size: 112.5, 75
            source: ".\control_bar_images\Start_Btn.png"
            center_x: self.parent.center_x
            center_y: self.parent.center_y
    Button:
        size: 112.5, 75
        pos: root.width/2+78.75, root.height-100
        background_color: 1, 1, 1, 0
        on_press: root.SO_pressing(SO_img, sm)
        Image:
            id: SO_img
            size: 112.5, 75
            background_color: 1, 1, 1, 0
            source: ".\control_bar_images\Stats_Btn.png"
            center_x: self.parent.center_x
            center_y: self.parent.center_y

Once I launch the app, the screen looks like this:

And when I put it in full screen, the screen becomes like this:

What should I do ?


text:
Q: How to use magnet links in LibTorrent lib How to use magnet links in LibTorrent C/C++ lib?
I need an simple example of working with it - Something like I give him a link he gives me a file.

A: While I haven't used it personally, but you could check http://www.qbittorrent.org/, it uses libtorrent internally and it is under the GPL-2 license.


text:
Q: Кол-во способов, которым можно вырезать прямоугольную область без закрашенных клеток Олимпиадное задача, для тех, кто хочет поломать голову:)
У нас есть листок в клетку размером n на m. К клеток в нем закрашены. Требуется посчитать кол-во способов, которыми можно вырезать прямоугольную область без закрашенных клеток. способы считаются различными, если в одной прямоугольной области есть хотя бы одна клетка, которая не принадлежит другой области. разрезать можно строго по линиям:)

1 <= n, m <= 5000
1 <= k <= 100000
1 <= k <= n*m

время 2 сек
A: Где-то так:
count:=0;
for left:=1 to n do
begin
  for right:=left to n do
  begin
    for top:=1 to m do
    begin
      for bottom:=top to m do
      begin
        {проверяем не наехал ли нижний край на закрашенную клетку}
        {если наехал, то break}
        {если не наехал, то inc(count)}
      end;
    end;
  end;
end;

Алгоритм медленный, при размерах поля 100*100 выполняется уже около 2 секунд.
UPD. Есть такая идея:

*

*Начинаем с первого столбца.

*Проходим по столбцу вниз пока не наткнемся на закрашенную клетку.

*Теперь "расширяем" столбец вправо, пока не наткнемся на закрашенную клетку.

*Для полученного прямоугольника считаем варианты по формуле: (height+1)*height/2*width

*Возвращаемся на левый столбец прямоугольника, перескакиваем через закрашенную клетку и переходим на пункт 3 и так пока не достигнем нижнего края.

*Сдвигаемся на столбец вправо и опять на пункт 2


text:
Q: C# Convert DatagridViewTextbox to DataGridViewComboBoxCell I have a DataGridView table that is already filled.
Now, when I click on a cell in the DataGridView, I want to make a ComboBox out of the cell, where I can then choose a selection of "Items".
Dgv_Data_List is my DataGridView.
        private void Dgv_Data_List_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
            DataGridViewComboBoxCell CboCell = new DataGridViewComboBoxCell();
            CboCell.Items.AddRange("Yes", "No");
            Dgv_Data_List.Rows[e.RowIndex].Cells[e.ColumnIndex] = CboCell;  <--At this point my program crashes
    }

I don't want any fixed comboboxes. They should be created at runtime as soon as they are needed.

A: It is unclear how the grid is filled with data. You may get away with this if the columns and rows are manually added, however if the grid has a DataSource, then when you "double-click" into a cell and set the cell as a combo box as you show… then the "current" cells value better be a "Yes" or "No" or you will get the grids DataError complaining about the value in the cell not being a valid combo box value.
I would think you would have to "delete" the current cells value just to avoid the possible error. Something like…
DataGridViewComboBoxCell CboCell = new DataGridViewComboBoxCell();
CboCell.Items.AddRange("Yes", "No");
Dgv_Data_List.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
Dgv_Data_List.Rows[e.RowIndex].Cells[e.ColumnIndex] = CboCell;

Setting the cells value to a blank string will work. HOWEVER, if the column type of the cells underlying data source is of a numeric type… then you will get the grids DataError complaining that the "Yes" or "No" value is not a valid numeric value… so technically this will ONLY work if the column type is a string type column. As most of this is unknown, I can only assume ALL the cells are of a string type.

A: As the code given, you created comboboxcell but not convert the grid view. so do this instead.
this.dataGridView1[CboCell] = new DataGridViewComboBoxCell();

Try this in the place of creating the comboboxcell.


text:
Q: How Can i pass Video Path to Another Activvity using Intent? Am Building an App which i want to customize my own Video Player within the App, I do not want to use default Android Media Player.
Activity 1:
 String VideoUri= fileUri.toString();
//            Intent videoIntent = new Intent(getListView().getContext(), VideoPlayerActivity.class);
//           videoIntent.putExtra("VideoPath", VideoUri);
//               startActivity(videoIntent);

Activity 2:
import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoPlayerActivity extends Activity {

    ProgressDialog myDialog;
    VideoView myvideoview;

    final String VideoUrl=getIntent().getExtras().getString("VideoPath");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_video_player);

        myvideoview = (VideoView) findViewById(R.id.uservideoView);

        myDialog = new ProgressDialog(VideoPlayerActivity.this);

        myDialog.setTitle("Video Loading");

        myDialog.setMessage("Streaming...");
        myDialog.setIndeterminate(false);
       myDialog.setCancelable(false);

        myDialog.show();

        try {

            MediaController mediacontroller = new MediaController(
                    VideoPlayerActivity.this);
            mediacontroller.setAnchorView(myvideoview);

            Uri video = Uri.parse(VideoUrl);
            myvideoview.setMediaController(mediacontroller);
            myvideoview.setVideoURI(video);

        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }

        videoview.requestFocus();
        videoview.setOnPreparedListener(new OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {
                myDialog.dismiss();
                myvideoview.start();
            }
        });

    }

}

Image Viewer works for me using Picasso API.  Is there any other way to Pass Video Uri Pass to a new Activity/

A: You can use Application Singleton Like this:
http://pastebin.com/JPRvAiv7


text:
Q: Modal box not showing asp.net I am trying to get a modal box to show. Whenever I click the button, it fades but the modal box does not show. Does anyone know the problem with my code?
asp:Button ID="searchMRF" UseSubmitBehavior="false" runat="server" CssClass="btn-primary active" Text="Search MRF No." Height="31px" Width="139px" data-toggle="modal" data-target="#TestModal" />
                                       <%-- MODAL --%>

                                                 <%-- MODAL CONTENT --%>

                                                         <asp:Button ID="close1" class="close" Text="x" runat="server" />
                                                         <asp:Label class="modal-title" runat="server" Text="TESTING"></asp:Label>

                                                         <asp:Label runat="server" class="modal-lg"></asp:Label>

                                                         <asp:Button ID="close2" runat="server" Text="Close" />


text:
Q: How to get all records that also "own" specific records performantly I have the following two models in Rails application
class Students < ApplicationRecord
  has_many :courses
  attr_accessor :name
end

class Courses < ApplicationRecord
  has_many :students
  attr_accessor :name, :course_id
end

I would like to get a a list of all courses shared for each student who has been in the same class as a selected student in an efficient manner.
Given the following students:

*

*Jerry's courses ["math", "english", "spanish"],

*Bob's courses ["math", "english", "french"],

*Frank's courses ["math", "basketweaving"]

*Harry's courses ["basketweaving"]
If the selected student was Jerry, I would like the following object returned
{ Bob: ["math", "english"], Frank: ["math"] }

I know this will be an expensive operation, but my gut tells me there's a better way than what I'm doing. Here's what I've tried:
# student with id:1 is selected student
courses = Student.find(1).courses

students_with_shared_classes = {}
courses.each do |course|
  students_in_course = Course.find(course.id).students
  students_in_course.each do |s|
    if students_with_shared_classes.key?(s.name)
      students_with_shared_classes[s.name].append(course.name)
    else
      students_with_shared_classes[s.name] = [course.name]
    end
  end
end

Are there any ActiveRecord or SQL tricks for a situation like this?

A: I think you're looking to do something like this:
student_id = 1
courses = Student.find(student_id).courses

other_students = Student
  .join(:courses)
  .eager_load(:courses)
  .where(courses: courses)
  .not.where(id: student_id)

This would give a collection of other students that took courses with only two db queries, and then you'd need to narrow down to the collection you're trying to create:
course_names = courses.map(&:name)
other_students.each_with_object({}) do |other_student, collection|
  course_names = other_student.courses.map(&:name)
  collection[other_student.name] = course_names.select { |course_name| course_names.include?(course_name) }
end

The above would build out collection where the key is the student names, and the values are the array of courses that match what student_id took.

A: Provided you setup a join model (as required unless you use has_and_belongs_to_many) you could query it directly and use an array aggregate:
# given the student 'jerry'
enrollments = Enrollment.joins(:course)
                        .joins(:student)
                        .select(
                          'students.name AS student_name',
                          'array_agg(courses.name) AS course_names'
                        )
                        .where(course_id: jerry.courses)
                        .where.not(student_id: jerry.id)
                        .group(:student_id)

array_agg is a Postgres specific function. On MySQL and I belive Oracle you can use JSON_ARRAYAGG to the same end. SQLite only has group_concat which returns a comma separated string.
If you want to get a hash from there you can do:
enrollments.each_with_object({}) do |e, hash|
  hash[e.student_name] = e.course_names
end

This option is not as database independent as Gavin Millers excellent answer but does all the work on the database side so that you don't have to iterate through the records in ruby and sort out the courses that they don't have in common.


text:
Q: Не отрабатывается скрипт на хостинге Не отрабатывается скрипт отправки писем на хосте. На локальной машине в OpenServer работает всё отлично, а на хосте нет, письма не уходят. И если отправляется форма с перезагрузкой, то всё работает, а форма с ajax нет, хотя функции идентичны. В php.ini запретов в disabled_function нет.

 $validator = Validator::make($request->all(), [
           'name' => 'required',
           'phone' => 'required',
           'date' => '',
           'captcha' => 'required',
           'captcha_two' => '',
       ]);

       if ($validator->passes() & $request->get('captcha') == $request->get('captcha_two')) {

           $newChallenge = new AppFeedback();

           $newChallenge->name    = $request->get('name');
           $newChallenge->phone   = $request->get('phone');
           $newChallenge->date   = $request->get('date');

           $newChallenge->save();

           //Здесь начинается отправка писем.

           $details = [
               'title' => 'Заявка на обратный звонок',
               'body' => 'Перезвоните клиенту!',
               'name' => 'Имя: '.$request->get('name'),
               'phone' => 'Номер: '.$request->get('phone'),
               'email' => '',
               'address' => '',
               'price' => '',
               'project' => '',
           ];

           $mails = DB::table('users')->get('email');

           foreach ($mails as $email) {
             \Mail::to($email)->send(new SendMail($details));
           }

           return response()->json(['success'=>'Отправлено!']);

       }

       return response()->json(['error'=>$validator->errors()]);


text:
Q: How to calculate filter coefficients for a polyphase filter I want to know the procedure to calculate filter coefficients for a polyphase digital filter. I want to interpolate image by factor 2 strictly in 1D. I have read some articles about polyphase digital filter working principle. My understanding about calculating filter coefficients is.. I need to know number of phases, taps and filter type for a polyphase digital filter, is this right?.
But I really don't understand on what factors the number of phases depends on, and how to calculate coefficients. It would be really helpful if someone can explain me.. I want to start with bilinear polyphase digital filter and then try bicubic.


text:
Q: Kiosk-like web application - how do I "lock" the app? Question: What's a good way to "lock" a Rails web application so a user must enter credentials to unlock it (but such that the user is still logged into the app and simply can't use the app without unlocking it)?
What I'm doing
I'm building a task management app that behaves like a kiosk to be used by multiple users. Users can log in to the app using their email address and password (full credentials), but once they're in, they can "swap" users by selecting their name from a list and entering a four-digit PIN (easy credentials).
Why have two types of credentials?
This is a multi-tenant app, and users use "full credentials" to simply get into the app and choose a tenant. Once they're in, they will frequently swap out as new employees come on shift and other employees leave because multiple employees will share a single work station.
Rather than forcing users to repeatedly enter their "full" credentials (by doing a full logout/login), I've created a name/PIN set of credentials they can use to easily swap. Once they're logged in with full credentials and have chosen their tenant, the app provides an autocomplete list of user's names, so it's very easy to select one's name from the list, enter the PIN and swap users.
Note that this "swapping" functionality is already built and working.
Why do I need to lock the app?
When a user is logged in to the app and a tenant, they may need to leave the app to go do other work. Without a lock screen, they only have two choices: fully log out so that the next user has to enter "full" credentials to use the app or just leave their account logged in for anyone to mess with.
I would like to allow them to click a button to "lock" the app when they walk away so that users can leave the app "logged in" without allowing other users to access others' accounts. Once they click "lock" all they can do is enter a name/PIN to unlock it, or click "sign out" to fully log out.
Here's what a typical use-case would look like:

*

*Frank logs into the app using his email address and password.

*He completes some tasks.

*Jane wants to use the app, so she "swaps in" by choosing her name from a list and entering her four-digit PIN.

*Now Jane is the logged-in user, meaning she can complete tasks, edit her profile, and other activities.

*Jane completes some tasks and needs to go do something else in the store, so she clicks the "Lock" button on the screen.

*The app is now locked and requires authentication to use (name and PIN) or the user can click "sign out" to fully go out of the app. The screen simply says something like "The app is locked. Enter your name and PIN to unlock it."

The options as I understand them
It seems like there are two ways to go here:

*

*JavaScript of some kind

*Some sort of controller logic using session variables or cookies

JavaScript makes me nervous because it's pretty hackable. I want to make sure the app is actually secure.
So I've been messing with ways of using session variables to do this. Here is what I've been trying:

*

*User is authenticated to the app for a particular tenant

*User clicks the "Lock" button

*A "lock_ui" action is called in the Sessions controller

*That action sets a few session variables (session[:locked], session[:locked_by], session[:locked_at])

*The app then always redirects to Sessions#locked, which displays the "This is locked. Enter name and PIN to unlock" form unless it's unlocked or the user clicks "sign out".

*Once a user enters a valid name/PIN, those session variables are deleted and the app functions normally.

Any suggestions on how I might do this so that it's secure?
Things I'm hung up on:

*

*Should I be using some sort of application controller filter (before or around) to check to see if the app is locked? What does the application controller do if the app is locked? (Does it call some other action, render a the "locked" page directly, or something else?)

*Or is this something that should be handled in the view layer? For example, I could update my application layout so it has an "if locked_ui render the 'locked' screen, else yield".

Some notes on how I'm currently set up:

*

*This is a Rails 4.1.0 app using Ruby 1.9.3 hosted on heroku.

*I'm using CanCan for authorization

*I'm using multi-tenancy with scopes (and I'm not using sub-domains)

*Each user has only one account that may have access to multiple tenants

*I've seen JQuery BlockUI, but it seems more like a vanity thing than a functional security device

A: Here's what I ended up building.
To answer my own questions:
Should I be using some sort of application controller filter (before or around) to check to see if the app is locked? I am using a before_filter in my Application Controller to check whether the UI is locked. If it's locked, I redirect to the "locked" screen. I then added a skip_before_filter to the relevant actions in my Sessions Controller (essentially ignoring that before_filter when the user is navigating to the "locked" screen and related lock/unlock actions in the Sessions controller.
Or is this something that should be handled in the view layer? In the view layer, I mostly just needed to create the actual "locked" screen (where a user enters credentials to unlock the app), and I make sure to hide navigation elements while the UI is locked (so the user isn't confused as to why they click "Edit Profile" and don't leave the lock screen).
I'm using cookies to record the current state of the UI (locked or not). Here are some code snippets:
application_controller.rb
before_filter :confirm_unlocked_ui

private

def confirm_unlocked_ui
  if signed_in? && locked_ui?
    redirect_to locked_path
  end
end

sessions_helper.rb
def locked_ui?
  session[:locked] == '1'
end

def lock_ui
  session[:locked] = '1'
  session[:locked_by] = current_user.id
  session[:locked_at] = Time.zone.now
end

def unlock_ui
  session.delete(:locked)
  session.delete(:locked_by)
  session.delete(:locked_at)
end

sessions_controller.rb
def lock
  session[:return_to] = params[:return_to] if params[:return_to]
  lock_ui

  redirect_to locked_path
end

def locked
  #essentially just a view
end

def unlock
  user = User.find_by_id(params[:session][:unlock_user_id])
  if user && user.authenticate_with_pin(params[:session][:pin])
    cookies[:auth_token] = user.auth_token
    unlock_ui
    redirect_back_or root_path
  else
    flash.now[:error] = "Invalid PIN."
    render 'locked'
  end
end

def destroy
  sign_out
  unlock_ui
  redirect_to root_path
end

I really don't know how "good" this solution is, and one reason I'm posting it here is to see if others come up with better ideas or see any issues lurking with how I've done this.
Some more subtle things you might want to think about if you're trying this:

*

*I'm using CanCan for authorization, and I've left that out here. If you have role-based authorization or something like that, be sure to check that this works for each role.

*Notice that I allow users to 'sign out' if they don't want to 'unlock'. I do this using the 'destroy' action my sessions controller and I make sure to 'unlock_ui' before I redirect them after signing out. If I didn't do this, then the app would still be "locked" the next time they log in from that browser.

*locked_path is an alias for Sessions#locked (basically just a view/form) that responds to a get request.

*Sessions#Lock also responds to get requests.

*Sessions#Unlock is what is called when the form is submitted from the "locked" view.


text:
Q: search suggestion - PHP - MySQL I have a MySQL query as below;
$query = "SELECT * FROM dictionary WHERE word LIKE '%".$word."%' ORDER BY word LIMIT 10";

This will search for (and display) words in my dictionary db.
the search will return;
Drunken for Drunk, etc, etc.. ,
Drunken for Drunke, etc, etc..
and Drunken for Drunken, etc, etc..
But it won't return Drunken for Drunkin. I would like to display this word as a suggestion word (like the one we see in google). How can I do this?
below is my complete code for reference;
$db = new pdo("mysql:host=localhost;dbname=dictionary", "root", "password");
$query = "SELECT * FROM dictionary WHERE word LIKE '%".$word."%' ORDER BY word LIMIT 10";
$result = $db->query($query);
$end_result = '';
if ($result) {
    while ( $r = $result->fetch(PDO::FETCH_ASSOC) ) {
        $end_result .= $r['word'].'<br>';
    }
}
echo $end_result;

A: Try Using SOUNDEX

Soundex keys have the property that words pronounced similarly produce
  the same soundex key, and can thus be used to simplify searches in
  databases where you know the pronunciation but not the spelling. This
  soundex function returns a string 4 characters long, starting with a
  letter.

Here are some questions on SO which may guide you in the right direction:

*

*How does the Google "Did you mean?" Algorithm work?

*How do you implement a "Did you mean"?
Hope this helps.

A: Soundex might help for simple cases, but if you want to implement something like this properly you'll need a Lucene search index where you can perform fuzzy (=unprecise) searches on. Have a look at the Apache Solr PHP port.

A: You will need something more complex than just a LIKE statement. It displays Drunken for Drunk because Drunken contains the word Drunk.
More complex algorithms look at the keyboard layout for possible typos: for example if you search for 'drumk' you could interprete that the letter M is next to N (on a QWERTY keyboard) and suggest drunk.
You could also try to remove the last character from the search query if there are no results:
For example: if you search for drunke and nothing is found, you can try searching for drunk and so on.
Hope this helps.

A: Just for the record, I am surprised there is no mention here of the levenshtein function, used for measuring the "distance" or similarity of two character strings, although it is true that for English words nothing seems to beat the soundex type algorithm or, more recently, Metaphone.
With a few lines of codes you will get the "Did you mean" from Google kind of stuff. See example #1 from the php.net documentation.
Note that this example is based on a static array of words. If you need to retrieve those words from your database, you will need to implement a few lines more...

A: Easiest way:
SELECT * FROM table_name WHERE soundex(field_name) LIKE CONCAT('%', soundex('searching_element'), '%')


text:
Q: Constructing a similarity matrix between points I have two images with two sets of corresponding points. In order to align the images I'm trying to compute the similarity matrix that describes the relationship between the corresponding points.
I know it's connected to affine transform:
[x y 1] = [u v 1] [a11 a12 0; a21 a22 0; a31 a32 1]

Rearranging the equation does [x y 1] / [u v 1] give the transform matrix?
Many thanks for any help you can give.

A: In Matlab, a = [x y 1] / [u v 1] gives the least squares solution to
a*[u v 1]=[x y 1]
where a is a scalar (not what you want).
To define an affine transformation in a plane, you need at least three points (and their corresponding points after the transformation).
If [x1 y1] goes to [u1 v1] etc., then what you want is
A = [[x1 y1 1];[x2 y2 1];[x3 y3 1]] \ [[u1 v1];[u2 v2];[u3 v3]].
That will make it so [x y 1]*A is the transformed position of [x y].


text:
Q: Spring Security Pages don't open in Iframe on Chrome I am using SpringBoot,springsecurity and jdk 1.8. When I am trying to open any secured thymleaf page in iframe on Chrome, then it is rediecting me to login page every time. It is working fine on firefox and IE. And When I try to open the same URL without iframe, it is working fine. I have already given much time to solve ,but could solve it. Below are my spring security conf file code. One more thing both domains are different.
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .headers()
                .frameOptions().disable()
                .and()
                .csrf().disable()/*disbaling csrf here*/
                .authorizeRequests()
                .antMatchers("/","/login","/css/**", "/js/**", "/fonts/**","/img/**").permitAll()/*do not use spring security on this path*/
                .and()
                .formLogin()
                .successHandler(successHandler) /*after success login on web we are handling the success event*/
                .permitAll()
                .and()
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login/?logout") /*defining logout and login url here*/
                .permitAll()
                 /*
                 * This is for authentication failure handling
                 * */
                 http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
                 /*Token based authentication we are handling here*/
                 http.addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService), BasicAuthenticationFilter.class);
                 http.addFilterAfter(new SameSiteFilter(), BasicAuthenticationFilter.class)
    }

Can anyone please help me on this?

A: To start off, I would advise you against disabling the "X-Frame-Options" header and using your appication in an iframe.
This poses a security risk, which you can read more about in this answer.
Now to explain the behaviour you are seeing.
Spring Security uses a Session cookie to store the user's session.
Cookies are associated with domains, so if, for example, there is a cookie associated with the domain stackoverflow.com then that cookie will be included in any request to stackoverlow.com.
In order to control that behaviour, cookies also have an attribute called SameSite.
The SameSite attribute can have 3 values, None, Lax, Strict or it can be unset and have no value.
When the value is None, it behaves as described above (included in all requests).
When the value is Lax, then the cookie will only be included in top level navigation GET requests.
The Session cookie that Spring Security uses does not set the SameSite attribute.
At this time (March 2020), some browsers, like Firefox and Edge, treat the unset attribute the same as None.
However, Chrome is experimenting with treating the unset attribute the same as Lax.
You can read more about that in the Chrome Platform Status.
In summary, when using Chrome, the Session cookie is treated as if it had SameSite set to Lax.
Since rendering an application in an iframe is not a top level navigation, the Session cookie is not included in the request from the iframe, and the application has no way of knowing that a user is signed in.
You can explicitly set the SameSite attribute to None by using Spring Session.
Again, I would caution against this, since it can make your application vulnerable to CSRF and clickjacking attacks.
If, after consider the security implications, you deem it necessary to set the SameSite attribute to None, you can do so by including Spring Session in your dependencies and creating a custom CookieSerializer.


text:
Q: Where to place limit clause? I am trying to place a limit clause on the database query to only show the first 4 results.
The current code I am working with is
    $categories_query = "select c.categories_id, cd.categories_name, c.parent_id
                      from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd
                       where c.categories_id = cd.categories_id
                       and c.categories_status=1 " .
//                             "and c.categories_id = ptc.category_id " .
//                             "and ptc.category_id = cd.categories_id " .
//                             "and ptc.product_type_id not in  " . $this->document_types_list . "
                       " and cd.language_id = '" . (int)$_SESSION['languages_id'] . "'
                         order by c.parent_id, c.sort_order, cd.categories_name";
         $categories = $db->Execute($categories_query);
         while (!$categories->EOF) {
           $this->data[$categories->fields['parent_id']][$categories->fields['categories_id']] = array('name' => $categories->fields['categories_name'], 'count' => 0);
           $categories->MoveNext();
         }

The problem that I am having is I found a way to limit only 4 results by placing LIMIT 4 after the order query, and it shows the first 4 parent categories, but it also removes the sub categories from the list.
So I want to take this

Menu One

Menu Two

Submenu One

Submenu Two

Submenu Three

Menu Three

Menu Four

Menu Five

ect...

and see this

Menu One

Menu Two

Submenu One

Submenu Two

Submenu Three

Menu Three

Menu Four

and when placing 'LIMIT 4' in the query it only shows this

Menu One

Menu Two

Menu Three

Menu Four

How do I keep the subcategories with the parent categories? Aparently calling only the first 4 does not call the categories under it

A: The query is doing exactly what you're asking it to do - "LIMIT" means you get just 4 records back, ordered by categoryID.
To get what you want, you have to rephrase the query - I haven't go SQL installed on this laptop, so it's hard to test, but something like this:
$categories_query = "select c.categories_id, cd.categories_name, c.parent_id
                      from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd
                       where c.categories_id = cd.categories_id
                       and c.categories_status=1 " .
                       " and cd.language_id = '" . (int)$_SESSION['languages_id'] . "'
                       " and c.parent_id in " .
                       " ( select parent_id from " . TABLE_CATEGORIES . " limit 4) " .
                       "  order by c.parent_id, c.sort_order, cd.categories_name";
         $categories = $db->Execute($categories_query);
         while (!$categories->EOF) {
           $this->data[$categories->fields['parent_id']][$categories->fields['categories_id']] = array('name' => $categories->fields['categories_name'], 'count' => 0);
           $categories->MoveNext();
         }


text:
Q: Case-Insensitive Maps? How is it that describes seem to return case-insensitive maps? For instance, if I create a new custom setting, the following succeeds:
Map<String, SObjectField> fields1 = SObjectType.MySetting__c.fields.getMap();
system.assert(fields1.containsKey('Id'));

yet the following fails:
Map<String, SObjectField> fields2 = new Map<String, SObjectField>();
fields2.putAll(SObjectType.MySetting__c.fields.getMap());
system.assert(fields2.containsKey('Id'));

However, their keysets are the same, as the following will pass:
system.assertEquals(fields1.keySet(), fields2.keySet());

In both cases, the keyset is:

["id","isdeleted","name","setupownerid","createddate","createdbyid","lastmodifieddate","lastmodifiedbyid","systemmodstamp"]

Clearly, only the lower case version of the string 'id' is in the map.
The same behavior seems to hold for Schema.getGlobalDescribe():
system.assert(Schema.getGlobalDescribe().containsKey('ACCOUNT'));

The above described behavior seems to violate the basics of how maps work in Apex. Is this in fact the same data structure? Can it be constructed by hand? It would potentially be useful, for instance, in parsing parameters on a page or REST service without needing to do some sort of loop through the keys with a case-insensitive comparison.

A: The docs outline the behaviour of the DescribeFieldResult map.  See Accessing All Field Describe Results for an sObject
There's a note saying:

The value type of this map is not a field describe result. Using the describe results would take too many system resources.
  Instead, it is a map of tokens that you can use to find the appropriate field. After you determine the field, generate the describe
  result for it.

It has the unique behaviour of:

*

*It is dynamic, that is, it is generated at runtime on the fields for that sObject.

*All field names are case insensitive.

*The keys use namespaces as required.

*The keys reflect whether the field is a custom object.

My understanding is that the keys are the tokens that have this unique behaviour, however in the second example, you're explicitly instantiating a new Map<String, String> with the DescribeFieldResult map in it.

A: Yes, describe maps break the usual case sensitivity rules. They are magical in nature. No, you can't directly replicate the behavior. You could use a wrapper class to store and retrieve only lowercase values using equals and hashCode method overrides, but you cannot construct a native map that's case insensitive.


text:
Q: data comes in a string, inserting into postgresql with java, what's most efficient way to break up the data? I am writing a program in Java that uses the JDBC driver with Postgresql. I am using an API which when called, returns data in a string like so:
id=-870229851 date = finished-20130501  15:13:07-20130502  15:13:07 open=-1.0 high=-1.0 low=-1.0 close=-1.0 volume=-1 count=-1 WAP=-1.0 hasGaps=false

Most of these names are a column in my Postgresql db (and I can make all of them a column if necessary), but I was wondering what is the most efficient way to insert this into Postgresql?
Before I write a function to parse each title / value, I'm hoping that Postgresql has some way of handling data like this efficiently.
Can someone please shed some light?
my Postgresql version is 9.2 and my Java is 1.7

A: Postrgre doesn't have a way to do this natively (that I know of anyway), however, you can use Java's string tokenizer like this:
StringTokenizer st = new StringTokenizer(sourceString, "= ");

while(st.hasMoreTokens()) {

  String key = st.nextToken();
  String valuse = st.nextToken();

  // Do something with the keys and values (i.e. build and execute insert statements.
}

Where sourceString is your data string. This will delimit the string based on both the equals sign and the space between the name value pairs. Assuming that no spaces occur in the name or values in the string. If they do, then you are going to have to do some regex magic on the string before tokenizing it, depending on that can occur on the left and right hand side of the equals sign.
Then you can generate insert statement strings to be executed by the database engine.


text:
Q: The relation of gamma matrix between field operator change and chirality in Peskin and Schroeder (page 165) I'm reading Compton scattering in Peskin's book (page 165) and there is a sentence I can't understand.

The third sentence in the above paragraph says that three $\gamma$-matrix between field operator guarantee that if the initial electron is right-handed, the final electron is right-handed. Additionally, in the next page, there is a sentence says two $\gamma$-matrix will convert a right handed-electron into a left-handed electron. Therefor I think in the amplitude between field operator the even number of $\gamma$-matrix will change the chirality while odd number $\gamma$-matrix will keep it.
I can't understand why it is the case that the even number of $\gamma$-matrix in the amplitude between field operator will change the chirality while odd number $\gamma$-matrix will keep it.
In fact, somebody had asked this question Why three gamma matrix between initial and final electron lead to the same helicity? but nobody gave an answer, so I ask this again.

A: Refer to the original equation (5.97), write $\gamma^i$ except $\gamma^o$ for $\overline{u}$, explictly
$$iM=...\overline{u}(p')\gamma^u\frac{\gamma^\alpha p_\alpha-\gamma^\beta k'_\beta+m}{(p-k')^2-m^2}\gamma^\nu u(p)$$
observe:
For right hand spinor, $\begin{pmatrix}0 \\ *\\ \end{pmatrix},$ we have $\gamma^\mu \begin{pmatrix}0 \\ *\\ \end{pmatrix} = \begin{pmatrix}0 & \sigma^\mu \\ \overline{\sigma}^\mu & 0\\ \end{pmatrix} \begin{pmatrix}0 \\ *\\ \end{pmatrix} =\begin{pmatrix}\sigma ^\mu *\\ 0\\ \end{pmatrix}$
For left hand spinor, $\begin{pmatrix} *\\ 0\\ \end{pmatrix},$ we have $ \gamma^\nu \begin{pmatrix}*\\ 0\\ \end{pmatrix} = \begin{pmatrix}0 & \sigma^\nu \\ \overline{\sigma}^\nu & 0\\ \end{pmatrix} \begin{pmatrix}*\\ 0\\ \end{pmatrix} =\begin{pmatrix}0\\ \overline{\sigma}^\nu *\\ \end{pmatrix}$
Thus every $\gamma^\alpha$ "flip" $\begin{pmatrix} *\\ .\\ \end{pmatrix}$ once and pick either $\sigma^\alpha$ or $\overline{\sigma}^\alpha$, and
in the original equation, two the dominate term had three $\gamma$, as $m$ is negligible in relativistic limit.
We begin with $u(p)=\begin{pmatrix}0 \\ u_R\\ \end{pmatrix}$, terms like
$$\overline{u}(p')\gamma^u \gamma^\alpha p_\alpha \gamma^\nu \begin{pmatrix}0 \\ u_R\\ \end{pmatrix}$$
$$=\overline{u}(p')\gamma^u \gamma^\alpha p_\alpha \begin{pmatrix} \sigma^\nu u_R\\ 0\\\end{pmatrix}$$
$$=\overline{u}(p')\gamma^u \begin{pmatrix} 0\\ \overline{\sigma}^\alpha p_\alpha \sigma^\nu u_R\\ \end{pmatrix}$$
Here, we write $\overline{u}(p')$ in terms of $\gamma^o$ but it does not pick up any $\sigma$ but just flip once more.
$$=u^+(p') \gamma^o \begin{pmatrix} \sigma^u \overline{\sigma}^\alpha p_\alpha \sigma^\nu u_R\\ 0\\ \end{pmatrix}$$
$$=u^+(p') \begin{pmatrix}0\\ \sigma^u \overline{\sigma}^\alpha p_\alpha \sigma^\nu u_R\\ \end{pmatrix}$$
$u^*(p')$ should be something like $\begin{pmatrix}0 \\ u_R^*\\ \end{pmatrix}$ for non-zero result.
$$=u_R^+(p') \sigma^u \overline{\sigma}^\alpha p_\alpha \sigma^\nu u_R(p) $$
$$=u_R^+(p') \sigma^u (\overline{\sigma}. p) \sigma^\nu u_R(p) $$
Thus both $u(p)$ and $u(p')$ are right hand and similarly you collect term by term, (5.99) is derived.

A: I am going to show an answer of my question based on my personal understanding.  The changing of chirality is in fact the result of below relation.
$\overline{u}(p^{\prime})\gamma^{\mu}(\frac{1+\gamma^{5}}{2})u(p)= u^{\dagger}(p^{\prime})(\frac{1+\gamma^{5}}{2})\gamma^{0}\gamma^{\mu}(\frac{1+\gamma^{5}}{2})u(p)=\overline{u}_{R}(p^{\prime})\gamma^{\mu}u_{R}(p)$
$\overline{u}(p^{\prime})\gamma^{v}\gamma^{\mu}(\frac{1+\gamma^{5}}{2})u(p)= u^{\dagger}(p^{\prime})(\frac{1-\gamma^{5}}{2})\gamma^{0}\gamma^{v}\gamma^{\mu}(\frac{1+\gamma^{5}}{2})u(p)=\overline{u}_{L}(p^{\prime})\gamma^{\mu}u_{R}(p)$
If the chirality of initial particle is determined, the chirality of the final particle is determined automatically according to the number of $\gamma$ matrix between field operator.
This is my current understanding, and I hope it could help people who is confused about it.


text:
Q: Querying the photos of a facebook page with age restriction I am the administrator of a Facebook page which needs to have an age restriction of 17+ on it.
On my website, I am making some Graph API queries, like querying photo albums and linking to them on Facebook. I am using the PHP Facebook API.
I can't seem to get to grips around the page access tokens and when they expire and when not.
I tried to follow this answer here, which was highly voted, but it isn't clear what you do with the first access_token after you copy it. I am not sure if this is even valid any more.
I tried to access the page using the access token I get when I do me/accounts in Graph Explorer and it works, but after some time it expires and I get an exception that the token expired. I need something that stays working and doesn't expire and need me to go in and update it.
This is the code I have so far:
$fbconfig = array();
$fbconfig['appId'] = DEF_APP_ID;
$fbconfig['secret'] = DEF_APP_SECRET;
$fbconfig['fileUpload'] = false;

Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;

$facebook = new Facebook($fbconfig);

//I am not sure if the following is the right way
$facebook->setAccessToken(DEF_ACCESS_TOKEN);
$facebook->setExtendedAccessToken();

...

try
{
    $albums_resp = $facebook->api('/'.$id.'/albums','GET');
    ...
}
catch (FacebookApiException $ex)
{
    error_log($ex);
}

What is the right way to achieve this?


text:
Q: Wrapping a C library with a streaming interface I've tried to give this a generic title to help future searchers, but concretely I am trying to parse YAML data. Import doesn't seem to support it natively and I can't find any code for it online, so I thought the easiest approach would be to wrap a C library (libyaml).
I haven't used the WSTP stuff yet, but the documentation looks pretty good at least for the easy cases, I was wondering if someone give give some tips though on

*

*How to either populate an Association from C or barring that at least populate a list of rules?

*How to deal with a "streaming" (e.g., SAX like) API? (See http://pyyaml.org/wiki/LibYAML#ParserAPISynopsis for a clean example).

A: You can use MathLink (recently called WSTP) for this.
MathLink is an interprocess communication protocol.  You can create links and send arbitrary Mathematica expressions through it.  This is the must-read tutorial for MathLink.  Use it in conjunction with the documentation.
Typically, you would create a function that is callable directly from Mathematica, e.g. by creating an installable MathLink program.  You will need to write the expression to be returned by this function to a MathLink link.  When using Installable programs, you simple set the return type to Manual in your template file and write to stdlink.
When parsing a YAML file, you probably need to anticipate errors and maybe just return $Failed if an error has occurred.  To deal with this I suggest not writing the expression to stdlink at first.  Instead, create a loopback link.  Write the parts of the expression to the link one by one, as you receive them from libyaml.  When you're finished, just transfer everything to stdlink.  If you must abort because of the error, throw away the contents of the loopback link, and MLPutSymbol a $Failed symbol in stdlink.

Sending associations is the same as sending any other expression.  Send them in the form Association[Rule["a", 1], Rule["b", 2]], etc.


text:
Q: n-dimensional matching algorithm Looking for some advice here.  Does anyone know a good place to start looking into matching algorithm in a n-dimensional space. For example, any dating site out there must be using some sort of algorithm to match 2 people.  What I have read is that we can map characteristics of a person in a n-dimensional array with a point system for each characteristic.  Once we have all (available) characteristics of a person, we can represent this person in a point within a n-dimensional array.  Then, to match 2 person would be as simple as finding the shortest distance between 2 point in this n-dim array.  Does anyone has any reference in implementation of these kind of algorithm?  What's the best language to write these kind of stuff in?

A: If you want to find the closest match for one person, Bentley & Shamos published a multi-dimensional divide-and-conquer method: Divide-and-conquer in O(N log N) time: Divide-and-conquer in multidimensional space in Proceedings of the eighth annual ACM symposium on Theory of computing 1976. If you can't get a copy this may also be helpful.
However for your example application actually finding the nearest neighbour doesn't seem to be the biggest problem - much trickier is mapping inputs into dimensions.  For example if one dimension is "likes animals", what value do you give to someone who likes dogs & cats but can't stand horses?  What about someone who loves horses, thinks dogs are OK, is annoyed by cats and is ambivalent about goldfish?

A: First off, pick the language you are most familiar with.  The algorithms for handling this are fairly straightforward, and should work in any modern language.  (As long as there is some concept of array, and potentially a matrix library, you should be fine.)  I've implemented many of these in C, C++, and C# before, but seen implementations in python, vb.net, etc.
Depending on what you are trying to do, there are a couple of options.
That being said, what you want to do depends on your goals.  If you just want to find the best match, you can use simple distance calculations (ie: sqrt of sum of squares for each dimension/property in the n-dimensional array), optionally weight each properties distance, and use the closest point.
If you want to group together people, you'll want to look at clustering algorithms.  For data like this, I would suspect that some form of K-Means clustering or fuzzy c-means clustering would work the best.

A: How about following solution.
Assume the users are U1, U2, U3, U4, U5.... Un.
Attributes are A1, A2, A3, A4, A5..... Am
Store these as
A1 - U1, U2, U3...
A2 - U4, U6, U7....
A3 -
Profile attribute is the index and stores all users. Now, if a new User comes, see the its attributes and for those attributes, find common people. number of times a person exists in these lists - higher ranking.

A: The process you mention is known as k-nearest neighbor, with k=1. It's the most intuitive approach for finding similar vectors.
http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm

A: What you describe with your example is not n-dimentional matching, but rather bipartite matching of nodes with multiple features. (You will need to provide a function that will, given two persons compute this distance). There should be very efficient algorithms for that. In n-dimentional matching you would try to match nodes from more than two sets (in your example, suppose you could cut people to body, soul, and music preferences, then recombine them to make new persons. Then the n-dimentional matching would cut the people apart, and recombine them so that the new persons engineered would make really nice couples :D ) Here is the wikipedia article for 3-dimentional matching, which is np-complete.
Also, as noted by another, if your goal is not to match persons in pairs, but rather find compatible groups, you should consider clustering them to groups. This can be done with e.g. Unsupervised Learning


text:
Q: How to include transiant depedency of springboot inside fabric mod I want to use spring boot inside fabric mod. And it works while I'm runing my minecraft server with gradlew.bat runServer command. But when I'm using gradlew.bat build and put the production jar inside a real server I got no class deff found error. Like that :
java.lang.RuntimeException: Could not execute entrypoint stage 'server' due to errors, provided by 'litopia_services'!
Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
       at fr.litopia.services.LitopiaServices.onInitializeServer(LitopiaServices.java:23) ~[litopia-services-1.0.0.jar:?]

And it's seems leagite cause inside the jar that gradle build there is'nt spring boot transiant depencency.
So to prevent this issue I have to use api insted of include or implement include but none of that have work actually my build.gradle looks like that :
plugins {
   id 'fabric-loom' version '0.11-SNAPSHOT'
   id 'org.springframework.boot' version '2.5.14'
   id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}

sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17

archivesBaseName = project.archives_base_name
version = project.mod_version
group = project.maven_group

repositories {
   // Add repositories to retrieve artifacts from in here.
   // You should only use this when depending on other mods because
   // Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
   // See https://docs.gradle.org/current/userguide/declaring_repositories.html
   // for more information about repositories.
   maven { url 'https://jitpack.io' }
   maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
   maven { url 'https://mvnrepository.com/artifac' }
   maven { url 'https://zoidberg.ukp.informatik.tu-darmstadt.de/artifactory/public-releases' }
   maven { url 'https://maven.terraformersmc.com/releases' }
   mavenCentral()
}

configurations {
   springBom
   compileOnly.extendsFrom(springBom)
   annotationProcessor.extendsFrom(springBom)
   implementation.extendsFrom(springBom)
   all {
      // We need to use fabric implementation of log4j
      exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
   }
}

dependencies {
   // To change the versions see the gradle.properties file
   minecraft "com.mojang:minecraft:${project.minecraft_version}"
   mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
   modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"

   // Fabric API. This is technically optional, but you probably want it anyway.
   modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"

   // Spring boot dependencies
   springBom enforcedPlatform('org.springframework.boot:spring-boot-dependencies:2.5.14')

   api include('org.springframework.boot:spring-boot-starter')
   implementation include('org.springframework.boot:spring-boot-dependencies:2.5.14')
   implementation include('org.springframework.boot:spring-boot-starter-web')
   implementation include('org.springframework.boot:spring-boot-starter-websocket')

   // OpenAPI swagger
   implementation include('org.springdoc:springdoc-openapi-ui:1.6.13')

   // Spring discord api
   implementation include('com.discord4j:discord4j-core:3.2.3')
}

processResources {
   inputs.property "version", project.version

   filesMatching("fabric.mod.json") {
      expand "version": project.version
   }
}

tasks.withType(JavaCompile).configureEach {
   it.options.release = 17
}

java {
   // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
   // if it is present.
   // If you remove this line, sources will not be generated.
   withSourcesJar()
}

jar {
   from("LICENSE") {
      rename { "${it}_${project.archivesBaseName}"}
   }
}


text:
Q: How to resolve a user that has not been interacted yet? I'm seeking a way to resolve a telegram user peer when it hasn't been interacted yet (e.g: I have a list of Telegram-Users Phone Numbers that tend to be invited to my Chat/Group/Channel) but aren't met/interacted yet, since there's no record for them in the local .session file, so there should be a way like search them in the Telegram-Database to resolve their Peer-Info needed to use to send the messages/invitations/...
Stay Safe V

A: There are different ways to resolve a user. If you have their phone number, you can do it using the method to import contacts:
import telethon

phone = "+123456789"  # Insert a phone here
contact1 = telethon.types.InputPhoneContact(
    client_id=12345,
    phone=phone,
    first_name="Name",
    last_name="Surname"
)
contacts = [contact1]
resolved_user = client(telethon.functions.contacts.ImportContactsRequest(
    contacts=contacts
))

The resolved_user variable will have the information about the found user which you can use in other methods for interaction.


text:
Q: view index, sort results export, pivot table python pandas I created a dataframe, table, from a pivot table in pandas.
df = pd.DataFrame({'v1':[5,5,6,6,1,5], 'v2':['c','a','b','a','a','b']})
table=pd.pivot_table(df,index=["v2"],values=["v1"],aggfunc=max)
table.sort_values(by='v1', ascending=True)

1) I would like to see also in the table the results of v2.
2) In order to sort I used a new line, is that possible to do it direclty in the pd.pivot_table sentence?
3) in real world some tables are too big to see in the console, what's the best way to export results, to better check them, exporting to .csv?
What I see in the console (Ipyhton shell) is this:
v2   v1
c    5
a    6
b    6

A: Instead of pivoting the table, a more straight forward alternative is grouped aggregation for your problem; To see v2 as a normal column instead of index, you can use reset_index(); the sort part has to be applied separately but you can chain the sort_values directly after other commands, if you prefer one liner; to see a big table in console, usually you can use .head() to view a few top rows of your table:
df.groupby('v2').max().reset_index().sort_values('v1', ascending=True)

#  v2   v1
#2  c   5
#0  a   6
#1  b   6

A: Consider resetting index and sorting directly on the pivot_table() call:
table = pd.pivot_table(df,index=["v2"],values=["v1"],aggfunc=max).reset_index().sort_values(by='v1', ascending=True)

print(table)
#   v2  v1
# 2  c   5
# 0  a   6
# 1  b   6


text:
Q: python not accept keyword arguments I am trying to make my code NOT to accept keyword arguments just like some bulitins also do not accept keyword arguments, but, I am unable to do so. Here, is my thinking according to my limited understanding:-
def somefunc(a,b):
    print a,b

somefunc(10,20)

Output:
10 20

Now, When I run the following (I know this is not expected to be keyword argument in the function definition, but, looking at the function call, it seems to be the same syntax as that of when calling a function which accepts keyword arguments):
somefunc(b=10,a=20)

Output:
20 10

I have 2 questions:-

*

*Looking at the function call somefunc(b=10,a=20) and not the function definition, this can seem to be either of a call to a function which accepts just normal arguments or a function which accepts keyword arguments. How does the interpreter differentiate between the two?

*Is it possible to convert any of our function in a form so that it does not accept keyword arguments just like many of the builtins do?

Why I want to do this at all?
I am just checking if I can do this, so that I do not miss anything in understanding python in depth. I do knot know whether python allows that or not.

A: You can use arbitrary argument lists to do this.  See http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists
For example:
def somefunc(*args):
    print args[0], args[1]

Calling without keywords:
somefunc(10,20)

Gives:
10 20

Calling with keywords:
somefunc(a=10,b=20)

Gives an error:
TypeError: someFunc() got an unexpected keyword argument 'a'

It's unclear why you would want to do this though.

A: ad 1) Correct names are verified automatically by Python if they are called like somefunct(name=value, ...). I need not to remember the exact standard order of parameters and to verify it too "neurotic" by looking into the documentation every month at every usage, if I remember a function with nice descriptive names of parameters and it will be tested that they are accepted by Python. On the contrary, the correct order of used parameters can be verified only by documentation. Calling by named parameters is preferred over very long list of positional parameters. Therefore the reported behaviour is well-founded. (Short single letter parameters "a, b" don't help against mistakes of course.)
ad 2) Some well known builtin fast functions written in C with small fixed number of required parameters do not support calling with named parameters. (e.g. hasattr)
This is because they use only simple header ...(... PyObject *args) and therefore all named parameters are rejected automatically. (Python can never introspect into names of arguments in C source. :-)
Many other C functions have a header ...(... PyObject *args, PyObject *kwds) and they support exact list of names explicitely by implementing much more complicated validation PyArg_ParseTupleAndKeywords and by writing the names to docs strings.

Edit: Positional-only parameters are possible in Python 3.8 by a new function parameter syntax / to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments.
def somefunc(a, b, /):
    print(a, b)

A:
Looking at the function call somefunc(b=10,a=20) and not the function definition, this can seem to be either of a call to a function which accepts just normal arguments or a function which accepts keyword arguments. How does the interpreter differentiate between the two?

Not sure if this is quite what you're asking, but if I understand you right, the answer is "it doesn't".  You can call the function with keywords no matter how the arguments are defined in the function.  If you pass any arguments using keyword syntax (e.g., f(a=...)), Python binds the corresponding values to the arguments with the same names in the function definition.  It doesn't matter whether a default value was defined.  The two kinds of function definition don't create different "kinds" of arguments, it's just that some of the arguments might have default values and others might not.  So whether you do def f(a) or def f(a=2), you can still do f(a=...).  The only restriction is that you have to pass/define positional arguments first (e.g., you can't do def f(a=2, b) or f(a=2, 3)).  See also this answer.
As for the second part of your question, I'm not aware of any way to stop a Python function from accepting keyword-passed values for named arguments.  If you define only *args then it won't accept keyword arguments, but the positional arguments can't have separate names.

A: There isn't such a strong distinction in Python between keyword and positional arguments. In fact, it is as simple as:
Positional arguments are parsed in the order they are listed in the function call
Keyword arguments can be added in any order, but cannot come before positional arguments.
So, if you have this:
def foo(x):
    pass

You can do:
foo(1) # positional
foo(x=1) # keyword

But you cannot do foo() because you didn't supply a default value.
Similarly, if you have this:
def foo(x,y='hello'):
    pass

foo(1) # this works fine
foo() # this is invalid, as an argument without a default isn't passed
foo(y='hello',1) # error - positional arguments come before keyword arguments

Don't forget to read up on arbitrary argument lists.

A: I think this is a very bad Python feature, and can lead to very unmaintainable and buggy code. Suppose you had a function:
def myurl(x, y):
    url = "{}:{}".format(x, y)
    return url

Although it might look like a good idea to enable replacing positional with keyword arguments don't ever do that. I'm surprised that there is no Python option that would prevent this function to be called with keyword arguments:
>> print myurl(x="localhost", y=8080)

If someone figures out the library would be more readable if written as:
def myurl(hostname, port):
    url = "{}:{}".format(hostname, port)
    return url

then the rest of the code that used keyword calling as myurl(x="localhost", y=8080) would fail:
TypeError: myurl() got an unexpected keyword argument 'x'

This means that your local function variable all of the sudden became a global variable! I was hoping this issue would be somehow addressed in Python 3.


text:
Q: Retrieving status data from printer/cartridge I'm inquiring whether is is possible to get:

*

*ink/tone level of a printers cartridge

*the cartridge model number

The platform and programming language is free. But I'm most interested in a Windows solution.
Also do you know if there is some work in progress for a standard on communicating with the printer - or if some specific brands have something already.

A: SNMP is the standard for most laser printer.  Manufactures have a MIB that describes how to get the information from it, these are often widely available as they are used to provide large network management systems access to details about these devices.


text:
Q: ipv6 ndptool for neighbor discovery I'm trying to collect all global IPv6 addresses in LAN. So I'm using ndptool to see how many addresses I could collect.
The command could report router broadcast:
# ndptool  -i eth1 monitor -t ra
NDP payload len 96, from addr: fe80::4e5e:cff:feea:365, iface: eth1
  Type: RA
  Hop limit: 64
  Managed address configuration: no
  Other configuration: yes

but I failed with NS or NA type:
# ndptool -t ns -i eth1 monitor

returns nothing.
I used tshark to capture icmpv6,  like:
tshark -R icmpv6 -i eth1

and it shows packets were received:
4533 43.369934717 2001:b030:214:100:4e5e:cff:feea:366 -> ff02::1:ff78:99f9 ICMPv6 86 Neighbor Solicitation for 2001:b030:214:100:48d0:319d:5b78:99f9 from 4c:5e:0c:ea:03:66
4578 44.014239120 fe80::1c41:89b5:6460:8e6d -> ff02::16     ICMPv6 110 Multicast Listener Report Message v2
4601 44.369626481 2001:b030:214:100:4e5e:cff:feea:366 -> ff02::1:ff78:99f9 ICMPv6 86 Neighbor Solicitation for 2001:b030:214:100:48d0:319d:5b78:99f9 from 4c:5e:0c:ea:03:66
4705 45.369780078 2001:b030:214:100:4e5e:cff:feea:366 -> ff02::1:ff78:99f9 ICMPv6 86 Neighbor Solicitation for 2001:b030:214:100:48d0:319d:5b78:99f9 from 4c:5e:0c:ea:03:66
4761 45.747995672 fe80::4e5e:cff:feea:366 -> ff02::1:ff93:9da3 ICMPv6 86 Neighbor Solicitation for 2001:b030:214:100:20c:29ff:fe93:9da3 from 4c:5e:0c:ea:03:66
4769 46.021538598 fe80::1c41:89b5:6460:8e6d -> ff02::16     ICMPv6 110 Multicast Listener Repo

It looks like the packets are there, but ndptool does not output them.
I hope to get the global IP and mac informations in LAN. How can I solve this?

A: ndptool is just a wrapper over Neighbor Discovery Protocol messages. So it allows only sending and receiving NDP messages. If I understand correctly the protocol messages (e.g. from How to: IPv6 Neighbor Discovery), an NA will be sent in response to an NS.
Try monitoring for NAs in one window, and sending NSs in another, and you will see that a neighbor responds with an NA.
Example, assuming eth0 and a neighbor with 2001:db8::2:

*

*in window A, run ndptool -t na -i eth0 monitor

*in window B, run ndptool -t ns -i eth0 -D 2001:db8::2 send

*in window A, observe NDP payload len 24, from addr: 2001:db8::2, iface: eth0 ...
If you need to know a neighbor's MAC address, try ndisc6
# ndisc6 2001:db8::2 eth0
Soliciting 2001:db8::2 (2001:db8::2) on eth0...
Target link-layer address: 02:42:AC:14:00:02
 from 2001:db8::2

or ip neighbor
# ip neigh show
2001:db8::2 dev eth0 lladdr 02:42:ac:14:00:02 STALE


text:
Q: Iphone 5S safari webpage zoom issue My scenario is I have iphone 5S device and safari browser. In this browser I opened a site (this site is included in bootstrap responsive also) with include below meta tag code.
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0">

If I opened the site with zoom in mode. everything is fine.
My problem is if open any other page of the same site it is showing zoom in view, but my requirement is if I open any page it will show normal view not in a zoom view. How can I do?
Shall I add any code in the meta tag? please suggest me

A: Use this
<meta id="id" name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

$(document).ready(function(){
    $("#id").attr("content", "width=device-width, initial-scale=1")
})


text:
Q: Not clear on one attribute value in shorthand version of background property? background: url(/rsrc.php/v2/yB/r/TwAHgQi2ZPB.png) 0 bottom repeat-x;

Can anyone tell what the 0 specifies in above property's value?

A: As you can see in the below screenshot, the 0 refers to the background-position. A unit need not be provided if the value is 0 and the browser automatically assigns the unit to it.
To be more precise it refers to X coordinate of the background-position or background-position-x.
Screenshot from Chrome's Dev Console:

Screenshot from Firefox's Dev Console:

Screenshot from Edge's Dev Console:


text:
Q: Is Huffman or arithmetic-encoded data read bit-by-bit when decompressed? Huffman and arithmetic-encoded data is used in many different compression programs for entropy encoding. They create a new encoding for symbols to be compressed that may not align to byte boundary. This means that when the data has to be decompressed, it must be read bit by bit. However, that seems to be very very slow process.
How is Huffman and arithmetic-encoded data decompression usually sped up? Do we create some sort of table as with CRC calculations, that enables us to read in data per byte and then decode the symbols or is it always really read in a per-bit basis?

A: Efficient Huffman decoders use tables. You can see an example in zlib's inflate, which uses two levels of tables to reduce the time needed to construct the tables.
Constraints can be placed on arithmetic codes to also permit them to use tables, and this is often done for speed, with only a small impact on compression.


text:
Q: Simple Page crashes Browser I have a simple list view built using JQuery Mobile.
It works fine on the desktop, but when you run it on Safari or Chrome on an iPhone (4S running 6.1), it crashes the browser.
I have put the link up on jsbin - http://jsbin.com/efehip/1
What could it be that causes the crash? There are no errors in the console on Desktop.
I can't see any tags that are incorrectly paired or anything else which should cause this issue.
Any ideas?

A: It's a very long list, it might be too much memory to load (though that sounds weird). You could try to page it so that it only loads a portion of the data. This will probably require server side scripting though.


text:
Q: OpenModelica internal error reinit called with wrong args? I'm writing a program that from an Functional Mock-Up Unit generates a complete Modelica model. It works just fine when I simulate the model in Dymola but in OpenModelica I get this error:
internal error reinit called with wrong args

I call reinit(states, fmiGetContinuousStates(...)); where fmiGetContinuousStates returns with the new states of the model after an event has been triggered. Does somebody know what causes this problem?
Edit:
Here is my model generated by my program. I now got an error Error: type in operand to change must be simple type in component <NO COMPONENT>.
within ;
package BouncingBall
 model BouncingBall_fmu
public
  constant String fmuInstanceName = "BouncingBall";
  constant String dll_path = "C:\\P418-FMIModelicaImport\\trunk\\fmu_path\\win32\\BouncingBall\\Resources\\Library\\binaries\\win32\\BouncingBall.dll";
  constant String GUID = "{7d4fc270-b710-45bd-abb1-b1aefef341ea}";
  parameter Boolean fmuLogger = true;
  parameter Real e = 0.700000 "coefficient of restitution";
  parameter Real g = 9.810000 "gravity acceleration";
  parameter Real h_start = 1.000000;
  Real h(start = h_start) "height of ball";
  Real der_h_ "der(height of ball)";
  parameter Real v_start = 0.000000;
  Real v(start = v_start) "velocity of ball";
  Real der_v_ "der(velocity of ball)";
  parameter Boolean flying_start = true;
  Boolean flying(start = flying_start) "true, the ball is flying";
  parameter Boolean impact_start = false;
  Boolean impact(start = impact_start);
  parameter Real v_new_start = 0.000000;
  Real v_new(start = v_new_start);
protected
  parameter Integer fmuNumberOfContinuousStates = 2;
  Real states[fmuNumberOfContinuousStates](each fixed=false)
    "The continuous states";
  parameter Integer fmuNumberOfEventIndicators = 4;
  Real eventIndicators[fmuNumberOfEventIndicators](each fixed = false)
    "Event indicators";
  Boolean domain_change[fmuNumberOfEventIndicators](each start = false)
    "Checks zero-crossing";
  fmiFunctions.FMU fmu = fmiFunctions.FMU(fmuInstanceName, fmuLogger, dll_path, GUID);
  parameter Real initNextTime(fixed = false);
  parameter Real startTime =  0.000000;

  Boolean newStates(start = false);
  Real tNext(start = initNextTime);
  Boolean stepEvent;
  Real states_set;
  Real states_and_inputs_set = states_set;
  Real der_states[fmuNumberOfContinuousStates];
  Real tempStates[fmuNumberOfContinuousStates](each start = 0);
   package fmiFunctions
     class FMU
      extends ExternalObject;
      function constructor "Initialize fmu model"
       extends Modelica.Icons.Function;
       input String instanceName;
       input Boolean loggingOn;
       input String dll_path;
       input String GUID;
       output FMU fmu;
      external"C" fmu = fmiInstantiateModel_wrapper(instanceName, loggingOn, dll_path, GUID)
       annotation (Include="#include <BouncingBall_wrappers.c>");
      end constructor;

      function destructor "Release storage of fmu model"
       extends Modelica.Icons.Function;
       input FMU fmu;
      external"C" fmiFreeModelInstance_wrapper(fmu);
       annotation (Include="#include <BouncingBall_wrappers.c>");
      end destructor;
     end FMU;

     function fmiSetTime
      input FMU fmu;
      input Real t;
     external"C" fmiSetTime_wrapper(fmu, t)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiSetTime;

     function fmiSetReal
      input FMU fmu;
      input Integer vr[:];
      input Real values[:];
      input Real inDummy;
      output Real outDummy = inDummy;
     external"C" fmiSetReal_wrapper(fmu, vr, size(vr,1), values)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiSetReal;

     function fmiInitialize
      input FMU fmu;
      output Real t;
     external"C" t = fmiInitialize_wrapper(fmu)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiInitialize;

     function fmiGetContinuousStates
      input FMU fmu;
      input Integer n;
      output Real x[n];
     external"C" fmiGetContinuousStates_wrapper(fmu, x, n)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiGetContinuousStates;

     function fmiGetNominalContinuousStates
      input FMU fmu;
      input Integer n;
      output Real x_nom[n];
     external"C" fmiGetNominalContinuousStates_wrapper(fmu, x_nom, n)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiGetNominalContinuousStates;

     function fmiGetReal
      input FMU fmu;
      input Integer vr[:];
      output Real values;
     external"C" fmiGetReal_wrapper(fmu, vr, size(vr,1), values)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiGetReal;

     function fmiGetInteger
      input FMU fmu;
      input Integer vr[:];
      output Integer values;
     external"C" fmiGetInteger_wrapper(fmu, vr, size(vr,1), values);
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiGetInteger;

     function fmiSetInteger
      input FMU fmu;
      input Integer vr[:];
      input Integer values[:];
     external"C" fmiSetInteger_wrapper(fmu, vr, size(vr,1), values);
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiSetInteger;

     function fmiGetString
      input FMU fmu;
      input Integer vr[:];
      output String values;
     external"C" fmiGetString_wrapper(fmu, vr, size(vr,1), values);
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiGetString;

     function fmiSetString
      input FMU fmu;
      input Integer vr[:];
      input Integer values[:];
     external"C" fmiSetString_wrapper(fmu, vr, size(vr,1), values);
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiSetString;

     function fmiGetDerivatives
      input FMU fmu;
      input Integer n;
      output Real derivatives[n];
     external"C" fmiGetDerivatives_wrapper(fmu, derivatives, n)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiGetDerivatives;

     function fmiSetContinuousStates
      input FMU fmu;
      input Real states[:];
      input Real inDummy;
      output Real outDummy = inDummy;
     external"C" fmiSetContinuousStates_wrapper(fmu, states, size(states,1))
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiSetContinuousStates;

     function fmiCompletedIntegratorStep
      input FMU fmu;
      input Real states_and_inputs_set;
      output Integer status;
     external"C" status = fmiCompletedIntegratorStep_wrapper(fmu)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiCompletedIntegratorStep;

     function fmiEventUpdate
      input FMU fmu;
      output Real nextTime;
      output Boolean newStates;
     external"C" newStates = fmiEventUpdate_wrapper(fmu, nextTime)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiEventUpdate;

     function fmiGetEventIndicators
      input FMU fmu;
      input Integer n;
      output Real eventIndicators[n];
     external"C" fmiGetEventIndicators_wrapper(fmu, eventIndicators, n)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiGetEventIndicators;

     function fmiGetBoolean
      input FMU fmu;
      input Integer vr[:];
      output Boolean values;
     external"C" fmiGetBoolean_wrapper(fmu, vr, size(vr,1), values)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiGetBoolean;

     function fmiSetBoolean
      input FMU fmu;
      input Integer vr[:];
      input Boolean values[:];
     external"C" fmiSetBoolean_wrapper(fmu, vr, size(vr,1), values)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiSetBoolean;

     function fmiSetDebugLogging
      input FMU fmu;
      input Boolean loggingOn;
     external"C" fmiSetDebugLogging_wrapper(fmu, loggingOn)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiSetDebugLogging;

     function fmiTerminate
      input FMU fmu;
     external"C" fmiTerminate_wrapper(fmu)
       annotation (Include="#include <BouncingBall_wrappers.c>");
     end fmiTerminate;
   end fmiFunctions;
 algorithm
  fmiFunctions.fmiSetTime(fmu, time);
  states_set := fmiFunctions.fmiSetContinuousStates(fmu, states, 1);
  der_states := fmiFunctions.fmiGetDerivatives(fmu, size(states,1));
  h := fmiFunctions.fmiGetReal(fmu, {33554432});
  der_h_ := fmiFunctions.fmiGetReal(fmu, {587202560});
  v := fmiFunctions.fmiGetReal(fmu, {33554433});
  der_v_ := fmiFunctions.fmiGetReal(fmu, {587202561});
  v_new := fmiFunctions.fmiGetReal(fmu, {637534210});
  flying :=fmiFunctions.fmiGetBoolean(fmu, {637534208});
  impact :=fmiFunctions.fmiGetBoolean(fmu, {637534209});
  eventIndicators := fmiFunctions.fmiGetEventIndicators(fmu, size(eventIndicators, 1));
  for i in 1:size(eventIndicators, 1) loop
   domain_change[i] := eventIndicators[i] > 0;
  end for;
  stepEvent := fmiFunctions.fmiCompletedIntegratorStep(fmu, states_and_inputs_set) > 0.5;

 equation
  der(states) = der_states;

  when cat(1, change(domain_change), {time >= pre(tNext) and pre(tNext) > 0, initial(), stepEvent}) then
   (tNext, newStates) = fmiFunctions.fmiEventUpdate(fmu);
  end when;

  when cat(1, change(domain_change), {time >= pre(tNext) and pre(tNext) > 0, initial(), stepEvent}) then
   if newStates then
     tempStates = fmiFunctions.fmiGetContinuousStates(fmu, fmuNumberOfContinuousStates);
   else
     tempStates = pre(tempStates);
   end if;
  end when;

  when cat(1, change(domain_change) and {newStates for i in 1:size(domain_change, 1)}, {time >= pre(tNext) and pre(tNext) > 0 and newStates, stepEvent and newStates}) then
    reinit(states, tempStates);
  end when;

 initial algorithm
  fmiFunctions.fmiSetReal(fmu, {16777216}, {e}, 1);
  fmiFunctions.fmiSetReal(fmu, {16777217}, {g}, 1);
  fmiFunctions.fmiSetReal(fmu, {33554432}, {h_start}, 1);
  fmiFunctions.fmiSetReal(fmu, {33554433}, {v_start}, 1);
  fmiFunctions.fmiSetBoolean(fmu, {637534208}, {flying_start});
  fmiFunctions.fmiSetBoolean(fmu, {637534209}, {impact_start});
  fmiFunctions.fmiSetReal(fmu, {637534210}, {v_new_start}, 1);
  fmiFunctions.fmiSetTime(fmu, startTime);
  initNextTime := fmiFunctions.fmiInitialize(fmu);
  states := fmiFunctions.fmiGetContinuousStates(fmu, size(states,1));
 end BouncingBall_fmu;

annotation (uses(Modelica(version="3.2")));
end BouncingBall;


text: Q: Ctrl+Click navigation on Eclipse RSE Just wondering if there is any workaround for ctrl+click navigation feature of Eclipse to work on Remote System Explorer (RSE)? I need to modify some Python packages which are hosted on a server and I access them through RSE. It will save me a lot of time if I can get the ctrl+click navigation working!


text:
Q: Remainder of summation of $g(n)$ when divided by $8$ I was given the following problem:
Let $g(n)$ be the smallest prime that divides $n^4+1$.
What is the remainder of $g(1)+g(2)+...+g(2015)$
when divided by $8$?
My attempt so far:
Instead of summing up then divide $8$, i tried to find the remainder of each individual $g(n)$ when divided by $8$, then sum them up, and reduce it with modular arithmetic. So clearly for $n$ odd, $g(n)$ leaves a remainder of $2$ when divided by $8$. But for $n$ even I have no clue how to proceed.
If you can help solving this, I will greatly appreciate it.

A: You're on the right track. As you noted, for odd $n$, we have that $n^4 + 1$ is even, and thus its smallest prime factor is $2$; i.e., $g(n) = 2$ for odd $n$.
On the other hand, for even $n$, we have that $n^4 + 1$ is odd, and thus its smallest prime factor is odd. Furthermore, if a prime $p$ divides $n^4 + 1$, it must be the case that $-1$ has a 4th root modulo $p$; for an odd prime $p$, this is the same as saying $1$ has a primitive 8th root. Because multiplicative groups modulo primes are cyclic (as multiplicative groups in any finite field are cyclic), this will happen if and only if $p - 1$ is divisible by $8$; thus $g(n)$ for even $n$ will be 1 modulo 8.
Combining these and the fact that in the range from 1 to 2015, there are 1008 odd and 1007 even values, our final answer is $1008 * 2 + 1007 * 1 = 7 \pmod 8$.


text:
Q: Audio combo-jack's microphone not working on Dell Latitude 5289 When I installed Kubuntu 18.04 on my Dell Latitude 5289 the audio combo jack didn't work. Luckily thanks to this comment on Launchpad I was able to make the headphones work by overriding pin 0x21 to "Headphone" using the HDAJackRetask utility.
The problem is, this didn't make the microphone on the headset work. I've tried various things for around two days and now it's time to ask for help since I don't want to become a level 3 Linux audiomancer.

*

*How to get microphone on the headset working?

*Is this a problem with BIOS/UEFI? I would like to get another opinion before I go complaining on Dell forums that their BIOS is broken for an OS which isn't supported by them.

Details:
I verified that the headset itself was working on another computer using the splitter (TRRS to TRS and TS; 4-pin connector to 3-pin and 2-pin). I was testing the earphone mic by tapping with a finger on the mic and expecting a sound spike and for comparison I was tapping near the laptop's built-in mic as well.
I tried what was suggested in some other questions and added to the file /etc/modprobe.d/alsa-base.conf the following lines (one at a time) with restart before testing.
options snd-hda-intel model=dell-headset-multi

options snd-hda-intel model=headset-mic

options snd-hda-intel model=laptop-amic

options snd-hda-intel index=0 model=dell-headset-multi

Maybe also (didn't write down, don't remember):
options snd-hda-intel model=laptop-dmic

Also I tried running the newest mainline kernel version via Ukuu tool (5.11 maybe? Sorry didn't write down). No noticeable difference.
Also I tried some slight fiddling around with pavucontrol and alsamixer. I hope I didn't break anything, but everything else is working.
Also throughout it all I tried a lot of overriding combinations of the unconnected pins of Realtek ALC3253. This syntax is from my own notes and indicates which pin was overridden to which device/function (disregard pin 0x21 which was needed for headphones output):
0x12=internal mic; 0x19=microphone; 0x1a=microphone; 0x21=headphones;
0x12=internal mic; 0x13=internal mic; 0x16=headphones; 0x17=headphones; 0x18=internal mic; 0x19=microphone; 0x1a=microphone; 0x1b=microphone; 0x1d=internal mic; 0x21=headphones;
0x12=internal mic; 0x16=headphones; 0x17=headphones; 0x19=microphone; 0x1a=microphone; 0x1b=microphone; 0x21=headphones;
0x12=internal mic; 0x13=internal mic; 0x16=headphones; 0x17=headphones; 0x18=internal mic; 0x1d=internal mic; 0x21=headphones;
0x12=internal mic; 0x13=internal mic; 0x18=internal mic; 0x19=microphone; 0x1a=microphone; 0x1b=microphone; 0x1d=internal mic; 0x21=headphones;
0x19=microphone; 0x1a=microphone; 0x1b=microphone; 0x21=headphones;
0x19=microphone; 0x1a=microphone; 0x21=headphones;
0x19=microphone; 0x1b=microphone; 0x21=headphones;
0x1a=microphone; 0x1b=microphone; 0x21=headphones;
0x19=microphone; 0x21=headphones;
0x1a=microphone; 0x21=headphones;
0x1b=microphone; 0x21=headphones;

I got the impression from this machine and another one that having an excessive pin overridden or missing one pin from overriding might be the difference between certain sound input or output working or not working. Since the combinatorics of this are too numerous to try out manually so I gave up.
In the above examples I was only meddling around with pins that had some kind of microphone output (without the extra possibilities of the "Advanced override" option) and I preferred "Microphone" over "Internal mic". The only other override I tried was "Headphones". Also I didn't see any "Headset mic" or "Headphone mic". I didn't try any "Dock Microphone" because it seemed irrelevant (and too many combinations!).
If you want me to list what all the possible overriding devices/functions were for each pin I can list them here as well.
I also have the poor descriptions of most of the results of pin overriding experiments displayed above. But for that I would need to make tables somehow...
Let me know what command outputs might be useful.