text:
Q: org.hibernate.MappingException: Unable to find column with logical name in Spring Hibernate I am converting Hibernate project to Spring Hibernate Project. Since I'm integrating Hibernate with Spring, I am defining all the session factory, datasource definition in @Configuration. After deployment, when I start the server, I am getting below exception
Unable to find column with logical name: TEST_CODE in org.hibernate.mapping.Table(TEST_MONTHS) and its related supertables and secondary tables.

EntityClass:
@javax.persistence.Entity
@Table(name="TEST_MONTHS")

public class ConnectionMonth implements Serializable {

    /**
     * @generated
     */
    private static final long serialVersionUID = -940496855L;

    @Id
    @Column(name = "TEST_CODE")
    private String testCode;

    @Id
    @Column(name = "CONMONTH")
    private String contractMonth;

    @Column(name = "TYPE")
    private String type;

    @Column(name = "STARTDATE")
    private Date startDate;

    @Column(name = "ENDDATE")
    private Date endDate;

    public String gettestCode() {
        return testCode;
    }

    public void settestCode(String testCode) {
        this.testCode = testCode;
    }

    public String getContractMonth() {
        return contractMonth;
    }

    public void setContractMonth(String contractMonth) {
        this.contractMonth = contractMonth;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    /**
     * @generated
     */
    @Override
    public String toString() {

        return "ContractMonth: " + contractMonth + " Type: " + type
                + " StartDate: " + startDate + " EndDate:  " + endDate;

    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((testCode == null) ? 0 : testCode.hashCode());
        result = prime * result
                + ((contractMonth == null) ? 0 : contractMonth.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ContractMonth other = (ContractMonth) obj;
        if (testCode == null) {
            if (other.testCode != null)
                return false;
        } else if (!testCode.equals(other.testCode))
            return false;
        if (contractMonth == null) {
            if (other.contractMonth != null)
                return false;
        } else if (!contractMonth.equals(other.contractMonth))
            return false;
        return true;
    }

}

Persistence Config:
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence.properties" })
@ComponentScan({ "com.test.commons.domain.*" })
public class PersistenceConfiguration {

    @Autowired
    private Environment env;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(restDataSource());
        sessionFactory.setPackagesToScan(new String[] {
                "com.test.commons.domain.employee"});
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

    @Bean
    public DataSource restDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));

        return dataSource;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(
            SessionFactory sessionFactory) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory);

        return txManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties hibernateProperties() {
        return new Properties() {
            {
                setProperty("hibernate.hbm2ddl.auto",
                        env.getProperty("hibernate.hbm2ddl.auto"));
                setProperty("hibernate.dialect",
                        env.getProperty("hibernate.dialect"));
                setProperty("hibernate.globally_quoted_identifiers", "true");
            }
        };
    }
}

persistence.properties:
# jdbc.X
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=/*DB url*/
jdbc.user=pwd
jdbc.pass=pwd

# hibernate.X
hibernate.dialect=org.hibernate.dialect.OracleDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop

A: Can you check table details in sql , is it having "" quotes around it or single quotes
As i also faced same issue in my code , in that i was having table details as below
CREATE TABLE `orders` (
`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`firstname` VARCHAR(50) NOT NULL,
);

And i was accessing it with below bean
@Entity
@Table(name="orders")
public class Order {

    @Id
    @GeneratedValue
    @Column(name="id")
    private int id;

    @Column(name="firstname")
    private String firstName;

    @OneToMany(targetEntity=OrderLine.class,
            cascade = CascadeType.ALL,
            fetch = FetchType.LAZY)
    @JoinTable(
            name="orderlines",
            joinColumns = {@JoinColumn(table = "orderlines", name="FK_orders_orders",
            referencedColumnName = "order_id")},
            inverseJoinColumns={@JoinColumn(table = "orders", name="FK_orders_orders",
            referencedColumnName = "id")}
            )

After removing single quotes it started working for me


text:
Q: How to have a mock controller pass data to a directive with Jasmine I am trying to unit test a directive with Jasmine:
app.directive('helloWorld', function() {
  return {
    restrict: 'E',
    scope: {
      messages: '=',
      onSelect: '&'
    },
    template: 'Test: {{ message.name }}',
    link: function(scope) {
    }
  }
});

Ideally, I would like to pass in some mock data for messages, and ensure that the DOM element in the directive is correctly populated.
But I cannot understand how to get the template to compile with the mock data. Specifically, messages: '&' means that the directive is watching whenever the controller updates messages. Here is the test:
describe('Directive: HelloWorld', function() {
    var $scope, ctrl, $compile, $rootScope;

    beforeEach(module('app'));

    beforeEach(inject(function(_$rootScope_, $controller, _$compile_) {
      $rootScope = _$rootScope_;
      $compile = _$compile_;
      $scope = $rootScope.$new();

      ctrl = $controller('MainCtrl', {
        $scope: $scope
      });
    }));

    it('should list three messages', function() {
      ctrl.messages = [{name: 'foo'}, {name: 'bar'}, {name: 'foobar'}];
      var template = '<hello-world messages="messages" on-select="ctrl.foo(message)"></hello-world>';
      var element = $compile(template)($scope);
      $rootScope.$digest();

      expect(element.children().length).toBe(3);
    });
  });

Here is the plunker: https://plnkr.co/edit/8Jy4eGXotduGvBsr8jkN?p=preview
I have looked at many SO questions, but I cannot yet make sense of it. How can I pass on data to the mock controller so that the template has access to it?
Update
I modified my Plunker to do this: $scope.messages = [{name: 'foo'}, {name: 'bar'}, {name: 'foobar'}]; instead of ctrl.messages = .... It works fine now.

A: You should be using $scope in your controller and exposing variables that you want to use in your templates by adding them to $scope instead of this.
See this plunk. The relevant changes to make the test pass are in MainCtrl code and line 21 of your test file. Also look at line 18 on index.html to see how to pass the scope variables in html.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stored Procedure With Named Parameters And Cursor I was reading on named parameters.  I actually have 2 questions:
If using named parameter syntax:  p_rank => 5, can I only pass what I need.  Say the procedure accepts 5 parameters, but for this call, I only want to pass 1 parameter.
Can I:  exec procedure_name(p_rank => 5) and not worry about the other 4?
Now with that, how can I use named parameters that have as output a REF CURSOR?
exec customer_package.retrieve_data (
  p_rank             => 5,
  p_value_score      => p_value,
  p_momentum_score   => p_momentum,
  p_growth_score     => p_growth,
  p_data             => p_output);

p_data is actually a REF CURSOR.......so, if calling using Positional Parameters from SQL Plus I can just define the variable as a REF_CURSOR and print it.  But this is being done in a stored procedure, calling another stored procedure, which is to return a REF CURSOR.......

A: To call proc as exec procedure_name(p_rank => 5) you should define other parameters with DEFAULT values. If you have OUT parameters like p_data, you should pass it to your proc anyway.


text:
Q: How to copy a folder maintaining symbolic links and junctions relative to the copy root? This might be a bit of an edge case, but I would dearly like to know if there is a simple way to achieve this.
Suppose I have the following set up (where the latter two are symbolic links to the first):

*

*D:\Work\CommonStuff

*D:\Work\Project1\Stuff -> D:\Work\CommonStuff

*D:\Work\Project2\Stuff -> D:\Work\CommonStuff

Now suppose I want to make a backup of D:\Work to E:\Work.
I would like the links to be maintained, relatively, resulting in:

*

*E:\Work\CommonStuff

*E:\Work\Project1\Stuff -> D:\Work\CommonStuff

*E:\Work\Project2\Stuff -> D:\Work\CommonStuff

Of course I understand that if I had:

*

*D:\Work\CommonStuff

*D:\Work\Project1\Stuff -> D:\Work\CommonStuff

*D:\Work\Project2\Stuff -> D:\Work\CommonStuff

*D:\Work\Project3\Stuff -> D:\OtherCommonStuff
Then it would complicate matters because if I am just copying D:\Work then what would the copy command do for the last option? In this case I'd like to copy the files directly, losing the symbolic link.
Is there any way robocopy or xcopy or [anyother]copy can achieve this on Windows 10?

A: Take a look at: Ln Command line hardlinks
This tool is kind of a NTFS Swiss Army Knife and can do lots of things, like create SmartCopies, which preserve the inner and outer Hardlink/Junction/SymbolicLink structure, does hardlink based incremental Backups and a lot of other things which can not be found anywhere.
I think what you ask can be achieved by:
ln.exe --unroll --copy --backup D:\Work E:\Work

--Unroll follows Outer Junctions/Symlink Directories and rebuilds the content of Outer Junctions/Symlink Directories inside the hierarchy at the destination location. Unroll also applies to Outer Symlink Files, which means, that unroll causes the target of Outer Symlink Files to be copied to the destination location.
--copy: Smart Copy basically creates a copy of the directory structure from the source location to the destination, but it preserves the inner hardlink structure and inner junction/symbolic link relations of the source, and recreates this inner hardlink structure and inner junction/symbolic link relation at the destination location.
--backup: Using the Backup Mode ACLs aka Access Control Lists, which contain the security for Files, Folders, Junctions or SymbolicLinks, and Encrypted Files are also copied.
ln.exe thus copies

*

*Alternative Streams on files and folders

*EA Records on files and folders (rarely used)

*Reparse Info

*File Attributes

*Timestamps: Creation Time, Last Access Time, Last Write Time

*Sparse Files and Alternative Sparse Streams

*Encrypted files

*ACLs


text:
Q: Windows Server 2022 Core: how to change default keyboard layout for all users (also login screen) I have a Server with Windows Server 2022 Core Standard and I set the language and time to US but the keyboard layout to German during installation.
However the keyboard layout is US by default for all users also on the login screen.
Does anyone know how to adjust?
What I have tried so far:
HKEY_CURRENT_USER\Keyboard Layout\Preload -> name:1, value:"00000407"
Works only for current user and not for login screen.
HKEY_USERS.DEFAULT\Keyboard Layout\Preload -> name:1, value:"00000407"
Changes back to "00000409" after new logout and login.

A: On Windows Server 2022, the cmdlet Copy-UserInternationalSettingsToSystem is available now. You can use this cmdlet to copy the Diplay Language, Input Language, Format and Location settings of your current user (with administrative privileges) to the system defaults.
I assume that you also need the german keyboard layout on the welcome screen, so that you can input your passwords correctly. Therefore, call Copy-UserInternationalSettingsToSystem with both of its switches:
Copy-UserInternationalSettingsToSystem -WelcomeScreen $True -NewUser $True


text:
Q: What is inside an Android APK file Coming form a web development background where all your files are uploaded to a server individually, the APK file is very different to me!
From what I gather it's kind of like a zip or exe file similar to software you install on a computer, e.g. Eclipse its self. Then when installed on a device the files and folders are extracted back into something similar to the file/folder structure I was working on in eclipse. And in which case I then again have access somehow to say the /res and /assets folders once the APK is installed?
Am I on the right track?

A: Android application package file. Each Android application is compiled and packaged in a single file that includes all of the application's code (.dex files), resources, assets, and manifest file. The application package file can have any name but must use the .apk extension (e.g., myExampleAppname.apk). For convenience, an application package file is often referred to as an .apk.

A: The structure of an APK:
|-- AndroidManifest.xml
|-- META-INF // Signature Data
|   |-- CERT.RSA
|   |-- CERT.SF
|   `-- MANIFEST.MF
|-- classes.dex //  java byte code file generated after the compilation
|-- res // resource files
|   |-- drawable
|   |   `-- icon.png
|   `-- layout
|       `-- main.xml
`-- resources.arsc

You can find more detailed information here:
http://android-anything.diandian.com/post/2011-09-28/5377936


text:
Q: Asynchronous delay in Lua? (like JavaScript setTimeout) I need to asynchronously delay execution of a function in Lua by X milliseconds. Can this be done?
Given a simple JavaScript example:
setTimeout(function() {
    alert('Hello world!');
}, 5000);

What's the Lua equivalent? Coroutines look like they may help, but I'm not sure.

A: Lua itself does not include asynchronous event support. If you're embedding Lua in something larger or using it with libraries, they may be able to provide callback support.

A: Try my lalarm library. It depends on alarm, which works in seconds, but can be easily changed to use ualarm if you have it.


text:
Q: One-dimension Algebraic groups I am searching for a possible analogue of a result in algebraic groups in a non-commutative setting, so I am looking for different proofs of the following :
Let $K$ be an algebraically closed field. A connected (affine) algebraic subgroup of $(K,+)^n$ having dimension $1$ is isomorphic to $(K,+)$.
Any ideas for elementary proofs ?
[Edit: let's stick here to characteristic 0; the characteristic $p$ case is in a separate question]

A: Maybe I missed something, but in the case where the characteristic is zero, it seems to be simple as follow: if $G$ is a closed subgroup of $(K,+)^n$ which is not trivial, then it contains an element $g$, and thus contains all powers of $g$, corresponding to $m\cdot g$, $m\in \mathbb{Z}$ (view $(K,+)^n$ as a vector space). The Zariski closure of this set is then $\{\lambda \cdot g\mid \lambda \in K\}$, which is a closed algebraic subgroup of dimension $1$, isomorphic to $(K,+)$. If $G$ is not equal to this group, it contains another element $h$, linearly independent with $g$ so contains $\{\lambda \cdot g +\mu h\mid \lambda,\mu \in K\}$, which has dimension $2$.


text:
Q: Dynamic merged Background I have a jpeg "screen" and a number from 0 to 255.
The jpeg is partially transparent.
The number should be used to achieve a grayscale Drawable like it is used in this example to set the background:
setBackgroundColor(Color.rgb(number, number, number));

Now, I want to programaticly merge these to values to get a single Image with the "number-Drawable" as Background and the jpeg overlaying it.
How can i achieve that?

A: You can use a LayerDrawable with a color drawable and a bitmap drawable as the layers. Please take care of supplying the transparency to the bitmap drawable as JPEG image format does not support transparency. Or use a PNG format for the "screen".


text:
Q: hide and animate when mouse over i want my div to hide when mouseover and turn animate instade and when mouserout div return.
so i did some thing like this.

so far i can only hide - every thing else not working =/
CSS
.htmlanimate {
    -webkit-animation-name: html5animate;
    /* Chrome, Safari, Opera / -webkit-animation-duration: 4s; / Chrome, Safari, Opera / -webkit-animation-iteration-count: 3; / Chrome, Safari, Opera */
    animation-name: html5animate;
    animation-duration: 4s;
    animation-iteration-count: 3;
}
@-webkit-keyframes html5animate {
    0% {
        border-left:10px solid red;
    }
    25% {
        border-top:10px solid red;
    }
    50% {
        border-right:10px solid red;
    }
    100% {
        border-bottom:10px solid red;
    }
}

A: I think this might help you, if i understood you better:
Demo

var img = document.getElementById('imageid');
var width = img.clientWidth;
var height = img.clientHeight;

$(".html5").hover(function(){
 $(".html5").css("height", height + "px");
 $(".html5").css("width", width + "px");
    $(".html5").addClass("htmlanimate");
    $("#imageid").fadeOut(500);

}, function(){
    $("#imageid").fadeIn(500);
 $(".html5").removeClass("htmlanimate");
});
.html5
{
   display:inline-block;
   border:10px solid transparent;
}
.htmlanimate {
    -webkit-animation-name: html5animate;
    /* Chrome, Safari, Opera / -webkit-animation-duration: 4s; / Chrome, Safari, Opera / -webkit-animation-iteration-count: 3; / Chrome, Safari, Opera */

    animation: html5animate 5s infinite;
    animation-iteration-count: 3;
}
@-webkit-keyframes html5animate {
    0%, 25% {
        border-left:10px solid red;
    }
    25%,50%,74%  {
        border-left:10px solid red;
        border-top:10px solid red;
    }
    75% {
        border-left:10px solid red;
        border-top:10px solid red;
        border-right:10px solid red;
    }
    100% {
        border-left:10px solid red;
        border-top:10px solid red;
        border-right:10px solid red;
        border-bottom:10px solid red;
    }
}


text:
Q: How to create reqular expression to match all numbers without the numbers at the beginning and end of the string? Example code:
test = '12asiudas8787hajshd986q756tgs87ta7d6-12js01'
test.scan(regexp)

As a result, I should get:
["8787", "986", "756", "87", "7", "6", "12"]

Like using a /\d+/ regexp, but without the numbers at the beginning and end of the string, in this case 12 and 01.

A: To match the numbers within the string use following regex.
Regex: (?<=[^\d])(\d+)(?=[^\d])
Explanation:

*

*(?<=[^\d]) Will ensure that it's not followed by a digit. Without this 2 of 12 at beginning will be matched too, and we don't want that.

*(\d+) matches your number.

*(?=[^\d]) Will ensure that last digit is not followed by a digit. Without this 0 of 01 will be matched too.
P.S: Edited regex on Wiktor Stribiżew's advice
One can also use \D instead of [^\d]. I used [^\d] to make it clear.
Regex101 Demo
Edited Regex101 Demo

A: test.scan(/(?<=\D)\d+(?=\D)/) # => ["8787", "986", "756", "87", "7", "6", "12"]

A: This should do:
test.scan(/(?<=[^\d])(\d+)(?=[^\d])/).flatten


text:
Q: SQLCMD: WHERE NOT LIKE I'm creating a batch file to export data using SQLCMD, the command look like this:
sqlcmd -S servername -d db1 -o c:\Temp\export.txt -Q "SELECT xColumn, yColumn FROM xTable1 WHERE xColumn NOT LIKE 'AB-C%'" -h-1 -s";" -W

The export works fine, but the only issue is WHERE xColumn NOT LIKE 'AB-C%'
Even with the NOT LIKE command, the data still appear in my export.txt file
EXPORTED DATA

EXPECTED RESULT

I tested my SQL command in SSMS and it works fine. The issue really seems to be when I run SQLCMD in Command Prompt


text: Q: When I connect to a VPN through Network Manager, DNS no longer works When I connect to my 3rd party VPN service using the network manager, the DNS lookups no longer work. /etc/resolv.conf specifies 127.0.1.1 as nameserver which is dnsmasq service. However, I need to manually add a nameserver of 192.168.1.1 which is my router before my VPN traffic will flow. How do I fix this? I'm using Ubuntu 16


text:
Q: Can't pass custom text to Facebook Wall Post - Android API I'm trying to allow the users of my app to publish stories on their walls from my application for things such as Achievements(for example) within my application. Here is the activity code, adapted from the HelloFacebookActivitySample:
With both activities, I can see my app name, description, and link no problem when I post. Using the latest version of the FB SDK. However, the string (message) that I pass through the newStatusUpdateRequest() method is not displayed.
(In this attempt, I'm trying to pass text from a text view)
The first way I tried it:
public class Settings_Facebook extends FragmentActivity {

    //Constants
    private static final String PERMISSION = "publish_actions";
    private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.MyApp:PendingAction";
    //Views
    private Button postStatusUpdateButton;
    private Button postPhotoButton;
    private LoginButton loginButton;
    private ProfilePictureView profilePictureView;
    private TextView greeting;
    //Variables
    private PendingAction pendingAction = PendingAction.NONE;
    private ViewGroup controlsContainer;
    private GraphUser user;
    private GraphPlace place;
    private List<GraphUser> tags;
    private boolean canPresentShareDialog;
    private enum PendingAction {
        NONE,
        POST_PHOTO,
        POST_STATUS_UPDATE
    }
    private UiLifecycleHelper uiHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
            pendingAction = PendingAction.valueOf(name);
        }

        setContentView(R.layout.activity_settings__facebook);

        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
            @Override
            public void onUserInfoFetched(GraphUser user) {
                Settings_Facebook.this.user = user;
                updateUI();
                // It's possible that we were waiting for this.user to be populated in order to post a
                // status update.
                handlePendingAction();
            }
        });

        profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
        greeting = (TextView) findViewById(R.id.greeting);

        postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
        postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onClickPostStatusUpdate();
            }
        });

        postPhotoButton = (Button) findViewById(R.id.postPhotoButton);
        postPhotoButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onClickPostPhoto();
            }
        });

        controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container);

        canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
                FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
    }

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };

    private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
            Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
            Log.d("HelloFacebook", "Success!");
        }
    };

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
        outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
    }

    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (pendingAction != PendingAction.NONE &&
                (exception instanceof FacebookOperationCanceledException ||
                exception instanceof FacebookAuthorizationException)) {
                new AlertDialog.Builder(Settings_Facebook.this)
                    .setTitle(R.string.cancelled)
                    .setMessage(R.string.permission_not_granted)
                    .setPositiveButton(R.string.ok, null)
                    .show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
        updateUI();
    }

    private void updateUI() {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());

        postStatusUpdateButton.setEnabled(enableButtons || canPresentShareDialog);
        postPhotoButton.setEnabled(enableButtons);

        if (enableButtons && user != null) {
            profilePictureView.setProfileId(user.getId());
            greeting.setText(getString(R.string.hello_user, user.getFirstName()));
        } else {
            profilePictureView.setProfileId(null);
            greeting.setText(null);
        }
    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {
            case POST_PHOTO:
                postPhoto();
                break;
            case POST_STATUS_UPDATE:
                postStatusUpdate();
                break;
        }
    }

    private interface GraphObjectWithId extends GraphObject {
        String getId();
    }

    private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = getString(R.string.success);
            String id = result.cast(GraphObjectWithId.class).getId();
            alertMessage = getString(R.string.successfully_posted_post, message, id);
        } else {
            title = getString(R.string.error);
            alertMessage = error.getErrorMessage();
        }

        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(alertMessage)
                .setPositiveButton(R.string.ok, null)
                .show();
    }

    private void onClickPostStatusUpdate() {
        performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
    }

    private FacebookDialog.ShareDialogBuilder createShareDialogBuilder() {
        return new FacebookDialog.ShareDialogBuilder(this)
                .setName("MyApplication")
                .setDescription("The description of the app")
                .setLink("https://play.google.com/store/");
    }

    private void postStatusUpdate() {
        final EditText simpleEditText = (EditText) findViewById(R.id.editStatus);
        final String message = simpleEditText.getText().toString();

        Bundle postParams = new Bundle();
        postParams.putString("name", "Facebook SDK for Android");
        postParams.putString("caption", "Build great social apps and get more installs.");
        postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
        postParams.putString("link", "https://developers.facebook.com/android");
        postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

        if (canPresentShareDialog) {
            FacebookDialog shareDialog = createShareDialogBuilder().build();
            uiHelper.trackPendingDialogCall(shareDialog.present());
        }
        else if (user != null && hasPublishPermission()) {
            Session session = Session.getActiveSession();
            Request request = new Request(session,"me/feed",postParams,HttpMethod.POST);

            RequestAsyncTask task = new RequestAsyncTask(request);
            task.execute();
//                    .newStatusUpdateRequest(Session.getActiveSession(), message, place, tags, new Request.Callback() {
//                        @Override
//                        public void onCompleted(Response response) {
//                            showPublishResult(message, response.getGraphObject(), response.getError());
//                        }
//                    });
//            request.executeAsync();
        }
        else {
            pendingAction = PendingAction.POST_STATUS_UPDATE;
        }
    }

    private void onClickPostPhoto() {
        performPublish(PendingAction.POST_PHOTO, false);
    }

    private void postPhoto() {
        if (hasPublishPermission()) {
            Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.button_focus);
            Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), image, new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
                }
            });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_PHOTO;
        }
    }

    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions");
    }

    private void performPublish(PendingAction action, boolean allowNoSession) {
        Session session = Session.getActiveSession();
        if (session != null) {
            pendingAction = action;
            if (hasPublishPermission()) {
                // We can do the action right away.
                handlePendingAction();
                return;
            } else if (session.isOpened()) {
                // We need to get new permissions, then complete the action when we get called back.
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
                return;
            }
        }

        if (allowNoSession) {
            pendingAction = action;
            handlePendingAction();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        uiHelper.onResume();
        updateUI();
    }
}

(in this attempt I'm passing a bundle of parameters)
The second way I tried it(Just the postStatusUpdate() method was changed):
 private void postStatusUpdate() {
        final EditText simpleEditText = (EditText) findViewById(R.id.editStatus);
        final String message = simpleEditText.getText().toString();

        Bundle postParams = new Bundle();
        postParams.putString("name", "Facebook SDK for Android");
        postParams.putString("caption", "Build great social apps and get more installs.");
        postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
        postParams.putString("link", "https://developers.facebook.com/android");
        postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

        if (canPresentShareDialog) {
            FacebookDialog shareDialog = createShareDialogBuilder().build();
            uiHelper.trackPendingDialogCall(shareDialog.present());
        }
        else if (user != null && hasPublishPermission()) {
            Session session = Session.getActiveSession();
            Request request = new Request(session,"me/feed",postParams,HttpMethod.POST);

            RequestAsyncTask task = new RequestAsyncTask(request);
            task.execute();
        }
        else {
            pendingAction = PendingAction.POST_STATUS_UPDATE;
        }
    }

A: For achievements, you can either use the Achievements API or Open Graph Actions/Objects. Since the Achievements are only available for games, Open Graph Actions are the way to go. Here are some links to get you started:

*

*https://developers.facebook.com/docs/opengraph/

*https://developers.facebook.com/docs/opengraph/getting-started/

*https://developers.facebook.com/docs/opengraph/using-actions/
Keep in mind that it may take some hours or even some days until the Open Graph Actions are accepted by Facebook.
You can also publish Open Graph Actions in the background without user confirmation, as long as the user can change the publishing in a settings dialog, for example.


text:
Q: How do I select a specific id from a JSON file in swift? I'm trying to just select one of the entries in my JSON file and am struggling to do so. Here is the list part of my code so far:
    var body: some View {

        NavigationView {
            Group {
                List {
                    ForEach(regions) { regions in
                   NavigationLink(destination: RegionsListView(regions: regions)) {
                       RegionButtonView(regions: regions)
                   }
              }
        }
            }
        }
        }

And here is the if statement:
    let regions: Region

    var body: some View {
        if regions.id != nil {
            SCaliView()
        } else if regions.id != nil {
            BAView()
        }
    }
}

struct Region: Codable, Identifiable {
    let id: Int
    let name: String
    let image: String

}

I want to make it so that when a certain id is selected, it will go to a certain view.

A: You can literally throw whatever kind of view you'd like after the case using a ViewBuilder. Text Views, Nested Stacks although its a little clear passing pre-constructed views. Just replace the Int with whatever you id type is, although Int should work and then modify the case statements to handle your different ids
 @ViewBuilder func jsonSelector(using id: Int) -> some View {
      switch id {
         case 0:
      ViewA()
         case 1:
      ViewB()
         case 2:
      ViewC()
         case 3:
      ViewD()

     }

}

Then just throw it in your view
jsonSelector(using: myID)
If you add some code, I'll edit the answer to fit your use case but this is a general fix


text:
Q: About Second Shifting Theorem Given equation:
$$y''+y=h(t)$$
initial conditions, $y(0)=1$ and $y'(0)=0$
where h(t+2$\pi$)=h(t)=$1$, if 0$\leq$t$\leq$$\pi$ or $0$, if $\pi$< t< 2$\pi$
Should I use Laplace Transform t-shifting to solve this question?

A: You have to use the Laplace transform formula for periiodic functionsLaplace transform formula for periiodic functions.
Your function is:
$$f(t)=u(t)-u(t-\pi)$$
Take the Laplace Transform of $f(t)$:
$$F(s)=\dfrac 1s- \dfrac {e^{-\pi s}} s$$
So that Laplace transform of $h(t)$ is:
$$H(s)=\left (\dfrac 1s- \dfrac {e^{-\pi s}} s \right)\dfrac {1}{1-e^{-2\pi s}}$$
$$H(s)=\dfrac 1 s\left ( \dfrac {1-e^{-\pi s}} {1-e^{-2\pi s}} \right)$$
The original equation:
$$y''+y=h(t)$$
Becomes:
$$Y(s)(s^2+1)-s=\dfrac 1 s\left ( \dfrac {1-e^{-\pi s}} {1-e^{-2\pi s}} \right)$$


text:
Q: Using EWS API send email method get 401 unauthorized I'm very new to EWS API. Now I've a problem when I Send Email using EWS sample. Still getting the error:
401 unauthorized.
Here is my sample code:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
  service.Credentials = new WebCredentials("user1@contoso.com", "password");
  service.TraceEnabled = true;
  service.TraceFlags = TraceFlags.All;
  service.AutodiscoverUrl("user1@contoso.com", RedirectionUrlValidationCallback);
  EmailMessage email = new EmailMessage(service);
  email.ToRecipients.Add("user1@contoso.com");
  email.Subject = "HelloWorld";
  email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API");
  email.Send();

The error in the email.Send() function. Any help for this?
Related link:https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/get-started-with-ews-managed-api-client-applications
I searched all links but no correct answer.

A: I've checked your provide link and not found any problem. In general, There is no problem in writing this way. The problem should be related to your server environment or account as wannadream mentioned.
You can refer to the following links:
"(401) Unauthorized" error when you use an EWS application to impersonate a user in Office365 Dedicated/ITAR
Exchange Web Service API and 401 unauthorized exception
Also, could you please change your account to test it?

A: Shot in the dark, but easy to try: several years ago I was getting unexplained 401s, and found some web post that mentioned adding an empty cookie container to the service object, i.e.:
service.CookieContainer = new CookieContainer();

It seemed to do the trick at the time, but not sure if it's still a thing.


text:
Q: Why is a transmitter dipole's ends the max/min voltage instead of the middle? If the AC voltage source is connected to the middle of the dipole, I'm confused on why the edges have the max/min voltage instead of the middle.
In my mind, the middle of the dipole is closer to the voltage source, and there is even some resistance between the middle of the dipole and the end, which would imply a voltage drop, making the dipole's end a lower voltage than the middle.
For a receiver, I understand why the ends have the max/min voltage (based on how the wave hits the dipole). However, I'm totally lost when it comes to a transmitter. Any help would be greatly appreciated.

A: On a dipole there is a spread of current and voltage, in very simple words: at the end of the dipole, no current is built up b/c it is an open end, so there the voltage rise to a maximum. The impedance at the ends of the dipole is very high compared to the impedance at the feed point.
I think, the wikipedia Web site explains this quite well.

A: Current and voltage are not especially good to present what happens in an antenna. The actual thing that happens in an antenna which is connected to a transmitter is that a radiowave comes along the feeding cable (it's in the space between the wires, in coaxial cable it's between the shield and the center wire). In antenna the fields spread to wider area and if the antenna is properly designed a substantial part continues to the free space around the antenna as wanted. The rest is dissipated in material losses or reflected back towards the transmitter.
The key thing is that there's a propagating wave around the antenna and some reflection happens at the far end from the feeding point. The current which the fields of the wave induce to the metal cannot jump out of metal in usual power levels, so the end of the metal surface is a discontinuity which causes reflection.
From the theory of transmission lines we should remember that when a wave meets a strict "no current possible any more" border the electric fields of the arriving and reflecting waves are in every moment to the same direction at that border, so the sum field of the arriving and reflecting waves is as strong as possible with that power level.
With transmission lines we usually call the RMS value of the sum field "standing wave" It's maximum is at the unconnected end of the line.
On the surface of an antenna less far from the feeding point the fields of the different direction propagating waves partially cancel each other (but do not disturb each other by any means) so the sum field can be weaker.
At the same time when waves propagate along the surface of the antenna they also lose energy to the space as radiated wave. That radiation is attempted to be maximized in antenna designs, in transmission lines it's wanted to be kept zero.
Voltage is a coarse measure for electric field, all vector field structure is omitted, but the proportionality to electric field strength is still there. Thus also voltage between the ends of a dipole antenna can be higher than at the feeding point.

A:
If the AC voltage source is connected to the middle of the dipole, I'm
  confused on why the edges have the max/min voltage instead of the
  middle.

Basically, an antenna converts the operating impedance of the electrical feed-circuit (circa 50 ohms) to that of free space. Given that free space has an impedance of 377 ohms (\$120\pi\$), the voltage to current ratio at the extremes of the antenna have to be greater than at the electrical feed-point (circa 50 ohms).


text:
Q: In this sentence, should "in" or "at" be used before "colleges", "parties", and "family reunions"?
She talked about shoes all the time: [...] college, [...] parties, and
  even [...] family reunions.

Which one should I use in the sentence above? (should I also include while?)

A: At would be appropriate. At is used to indicate places or activities. In could be used for college ("in college") as it's valid to do something inside a location such as a college. It's not correct to do something in a party, as a party is not a location.

She talked about shoes all the time at college, at parties and even at family reunions.


text:
Q: What does $\sum_{i\in I}a_i x_i$ look like when $I=\emptyset$? Let $X$ be a (potentially infinite dimensional) vector space, and suppose that $x\in X$. Take the finite indexing set $I$, which corresponds to the basis of $X$. That is, we can find $a_i$ in $\mathbb F$, for $i\in I$, such that $\sum_{i\in I}a_i x_i=x$. Additionally, let $b_j$ in $\mathbb F$ for $j\in J$, where $J$ is another finite indexing set, and consider the product
$$x\cdot\sum_{j\in J}b_j=\sum_{i\in I}a_i x_i\sum_{j\in J}b_j=\sum_{j\in J}\sum_{i\in I}a_ib_j x_i,$$
where the order of summation doesn't matter, since all sums involved are finite.
My question: if $I=\emptyset$, then what does this product look like? Is it, since $I$ is empty and there is no $x_i$ which can be indexed by anything there, that $\sum_{i\in I}a_i x_i=0$, which would mean $x\cdot\sum_{j\in J}b_j=0$? Or, is it that $\sum_{i\in I}a_i x_i=1$ so that $x\cdot\sum_{j\in J}b_j=\sum_{j\in J}b_j$?

A: Well, the convention is that an empty sum, i.e., $I=\emptyset$, equals the zero element in the structure (vector space, ring, etc.), here zero vector,  and - what's not so important for you - an empty product equals the unit element in the ring.


text:
Q: Example of a sum of complete vector fields Can anyone give an example of two vector fields $X_1$ and $X_2$ which are complete but their sum $X_1+X_2$ is not complete?

A: Let $M = \mathbb{R}$, $X_1 = (\sin^2{x}) x^2 \frac{\partial}{\partial x}$ and $X_2 = (\cos^2{x}) x^2 \frac{\partial}{\partial x}$. Then $X_i$ are complete but $X_1 + X_2 = x^2 \frac{\partial}{\partial x}$ which is not complete.
Why is $X_1$ complete? If $\alpha \colon I \rightarrow \mathbb{R}$ is an integral curve of $X_1$ satisfying $\alpha(0) = t$ for some $t \in \mathbb{R}$ then either $\alpha \equiv 0$ (if $t = \pi k$ for some $k \in \mathbb{Z}$) or $\alpha(I) \subset (\pi k, \pi (k + 1))$ (if $\pi k < t < \pi (k + 1)$ for $k \in \mathbb{Z}$) which both imply that $I = \mathbb{R}$. Similarly for $X_2$.

A: Consider the complete vector fields $X = y^2 \frac{\partial}{\partial x}$ and $Y = x^2 \frac{\partial}{\partial y}$ defined on $\mathbb R^2$. We have that $X + Y $ is not complete. In order to see that it suffices to find the solution of $$\begin{cases}\frac{dx}{dt}  = y^2 \\ \frac{dy}{dt} = x^2\end{cases}$$ when $(c,c)$ moves along $x = y$.


text:
Q: Windows Guest VM no internet on Ubuntu KVM host I installed Windows 7 as a guest in KVM running on Ubuntu 12. Windows seems to be running fine with the exception that it can't access any external domains or IPs.
The guest can ping the host's IP and the host can ping the guest's IP, but that's it.
I used the default NAT setup, which others have reported should work. What can I do to fix this?
Edit: I also have VirtualBox running on the same host, also running a Windows VM, and it's internet works just fine.
Edit: The Ubuntu host's routing table:
user@localhost:~$ netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         192.168.1.1     0.0.0.0         UG        0 0          0 eth2
169.254.0.0     0.0.0.0         255.255.0.0     U         0 0          0 eth2
192.168.1.0     0.0.0.0         255.255.255.0   U         0 0          0 eth2
192.168.122.0   0.0.0.0         255.255.255.0   U         0 0          0 virbr0

The virbr0 is some old bridge leftover from when I tried setting up bridging in Virtualbox, but it's no longer used since Virtualbox works find with NAT. I did try using it with KVM, but had no success.

A: After some discussion on the oftc-channel #virt, @laine pointed me to the solution.
Apparently, the resolv.conf file is missing on ubuntu 12.04 (at least on my installation of linux mint 13). It is replaced by some resolvconf directory tree.
To enable internet on the guests: I had to

*

*sudo iptables --flush
=> on the host, might be obsolete, I don't know that. It cleared some rules.

*add "nameserver8.8.8.8" to /etc/resolv.conf

*reboot

After that, it worked
EDIT: note that step 2 was also performed on the host. I think it was linux mint (ubuntu 12.04), which was missing the /etc/resolv.conf file.

A: Is there some reason you can't use bridged networking? I always run in bridged mode when the VMs need to have access to the Internet, and I generally recommend it (you haven't given any reason why bridged mode might not be a good idea). The VMs are then treated as first-class citizens as far as network connectivity is concerned.

A: You're using the wrong NIC on the VM. I used to run xp/7/8 on ubuntu 12.04 on Oracle virtualbox without issue. don't use nat host only type NICs. use the option that gives you a physical address on the network, that way you have a single hop to the gateway.


text:
Q: Smooth Scrolling (alternative solution needed) I have used this snippet for Smooth Scrolling in one of my template. Source:http://css-tricks.com/snippets/jquery/smooth-scrolling/
<script>
    $(function() {
        $('a[href*=#]:not([href=#])').click(function() {
          if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
              && location.hostname == this.hostname) {

            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
              $('html,body').animate({
                scrollTop: target.offset().top
              }, 1000);
              return false;
            }
          }
        });
      });
    </script>

But this causes problem(the modal just doesn't show up) with my twitter Bootstrap Modal's javascript code:
<!-- Modal -->
    <script>

 $(function() {
    $("input#submitt").click(function(){
               $.ajax({
                    type: "POST",
                    url: "process.php",
                    data: $('form#contact').serialize(),
                    success: function(msg){
                    alert("success: " + msg);
                     $("#form-content").modal('hide');
                 },
                    error: function(){
                    alert("failure");
                    }
                });
    });
});
</script>

If I remove the Smooth Scrolling code, my modal works just fine. I'm looking for an alternative for smooth scrolling or any improvement in the existing one.


text:
Q: Wordpress tabs jQuery hasClass I want to add to the body a class when a li has active class.
Here is my html:

        Trape de fum

        Luminatoare

      Fatade

      Copertine

And here is the jQuery that I used to add the class:

if ( $('.ui-tabs-nav li:first-child').hasClass('ui-tabs-active') ) {
            $('body').addClass('firstli');
        }

I thought that I'm not doing it the right way, but i tried with the #primary div and it worked, it inserted the class into the body. So I think the problem is not with the jQuery.
So long story short, I want when the li has the class ui-tabs-active to add to the body the class firstli.
Also I'm doing this to a wordpress website.
And the piece of html is from the Tabs Shortcode for wordpress.
Thank you in advance.

A: First make sure that isn't the problem the dollar sign($).
The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.
In the noConflict() mode, the global $ shortcut for jQuery is not available, so you can still use:
jQuery(document).ready(function(){
    jQuery(#somefunction) ...
});

More : https://codex.wordpress.org/Function_Reference/wp_enqueue_script

A: Here is the resolution for the problem that i posted
 $('#squelch-taas-tab-group-0 ul li').click(function() {
    var id = $(this).find('a').eq(0).attr('id');
    $('#page').addClass(id);
    if ($('#squelch-taas-tab-group-0').data('lastid')) {
        $('#page').removeClass($('#squelch-taas-tab-group-0').data('lastid'));
    }
    $('#squelch-taas-tab-group-0').data('lastid', id);
});


text:
Q: Does Visual Studio 2010 on x64 crash often? Or is it just on my PC? MY VS2010 crashes dozens of times a day.  Compare that to 2008 and 2005 which were rock solid.
Is 2010 known to be susceptible to crashing? Or could it be my environment? I'm using x64 as a dev box for the first time.  The only plugin I has so far is Ankh.
It crashes when doing different things.  One I've noticed so far that always happens is if I press the key sequence alt-f-s-up (or any cursor key) it will crash every time.

A: The older versions of AnkSVN had a bug that caused constant crashing in VS2010 (1x per hour or more).  Upgrade to 2.1.8420 or later.

A: It never crashes on my laptop. But still I find it slower than VS2008. Maybe because of the new powerful features.

A: VS2010 is solid for me on x64.
Is that key sequence tied to Ankh? If so that might be the cause.  Does this sequence also crash VS if you use it in a new project?

A: No crashes here, been running VS2010 on Win7x64 for quite awhile.  Are you using version control? Try removing that plugin you mentioned, at least for a while, to see if the crash rate changes.

A: I had around 5 crashes last few days on Win7 Pro x64. And it happend without any concrete reason...

A: I found intresting page http://www.jetbrains.net/devnet/thread/288025.
This problem can appear with Resharper 5 and TODO statement in your code.

A: Mine freezes the whole system on debugging from time to time. It may freeze when I start debugging for a program or after some time the debugging has been started.
Here is what I found:
http://blogs.msdn.com/b/debugger/archive/2010/01/06/visual-studio-2010-beta2-hang-while-debugging.aspx
I have disabled the IntelliTrace, but today got another hang.


text:
Q: Can I tell if a given URL is a Facebook Instant Article? Given a URL, can I tell if it's a Facebook Instant Article without posting it on Facebook?

A: Yes, you can make a request to the Graph API and request the field instant_article of the object.
For example a request for a NYT article would return the following result:
{
  "instant_article": {
    "id": "1060796090661757"
  },
  "id": "http://www.nytimes.com/2016/06/11/science/milky-way-light-pollution-dark-skies.html"
}

The request for this would be:
GET https://graph.facebook.com/v2.6/?id=ARTICLE_URL&fields=instant_article&access_token=YOUR_ACCESS_TOKEN


text:
Q: Kafka Avro Deserialization Exception I am using Avro maven plugin to autogenerate the schema for .avsc file. In my AVSC i have one field defined as
{
        "name": "priceUSD",
        "type": [
            "null",
            {
                "type": "bytes",
                "scale": 5,
                "precision": 20,
                "connect.version": 1,
                "connect.parameters": {
                    "scale": "5",
                    "connect.decimal.precision": "20"
                },
                "connect.name": "org.apache.kafka.connect.data.Decimal",
                "logicalType": "decimal"
            }
        ],
        "default": null
    }

But when i am consuming the record i am getting "ClassCastException: java.math.BigDecimal cannot be cast to java.nio.ByteBuffer"
My application.yaml have configuration as below :
spring:
  kafka:
    producer:
      value-serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
      key-serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
      bootstrap-servers: localhost:9092
      specific:
        avro:
          reader: 'true'
    properties:
      basic:
        auth:
          credentials:
            source: USER_INFO
          user:
            info: ${schema_registry_api_key}:${schema_registry_api_secret}
      specific:
        avro:
          reader: true
      schema:
        registry:
          url: http://localhost:8081
      sasl:
        jaas:
          config: org.apache.kafka.common.security.plain.PlainLoginModule required
            username="${kafka_api_key}" password="${kafka_api_secret}";
        mechanism: PLAIN
      security:
        protocol: PLAINTEXT
      spring.deserializer.value.delegate.class: io.confluent.kafka.serializers.KafkaAvroDeserializer
      spring.deserializer.key.delegate.class: io.confluent.kafka.serializers.KafkaAvroDeserializer
    consumer:
      useNativeEncoding: true
      key-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
      value-deserializer: org.springframework.kafka.support.serializer.ErrorHandlingDeserializer
      bootstrapServers: localhost:9092

I have tried maven configuration with my plugin as below but that also doesn't seem to help
true
Please help me understand what i am missing here.


text:
Q: Quantum analogue of Wiener process The Wiener process (say, on $\mathbb{R}$) can be thought of as a scaling limit of a classical, discrete random walk. On the other hand, one can define and study quantum random walks, when the underlying stochastic process is governed by a unitary transform + measurement (for an excellent introduction, see http://arxiv.org/abs/quant-ph/0303081).
My question is - do quantum random walks have a reasonable continuous limit, something which would give a quantum analogue of the Wiener process?

A: I believe that The theory of quantum sochastic processes of Hudson and Parthasarathy,
(see the original article) provides the necessary generalization to the continuous limit and also to a more general quantum evolution semigroups.

A: In section III.B of the survey paper you cite, it describes continuous quantum walks, which are I think are a natural analogue of the Wiener process.  These are basically Hamiltonian evolution when the Hamiltonian is something like the adjacency matrix (or Laplacian) of a graph.
On the relationship between continuous- and discrete-time quantum walk has some recent developments with fascinating applications to simulating Hamiltonians on quantum computers.


text:
Q: Joomla redirects wrong after POST Situation: FreeBSD 13 server with Apache 2.4 as reverse proxy on SSL.
Bastille jail with nginx on port 80 and joomla 4.04
Problem: When doing a POST within Joomla (actually any POST except the one from logging in), the update gets handled okay but it then redirects back to the original full URL without a trailing slash. This cannot, of course, be resolved at the DNS level and results in a 404.
I tried replacing nginx with apache 2.4 but the problem stays.
In the Joomla configuration.php file I tried several options for the $live_url value (including a trailing backslash) but that didn't do the trick either. (tbh I didn't see any difference if it had a value or not).
As I'm new to Joomla, I didn't found any way of debugging to see where exactly this goes wrong and how to fix it.

A: As it turned out, the problem was caused by the front-facing Apache reverse proxy server, where in the http redirect to https the trailing '/' was missing.
And because joomla gives a 303 (see other) to the non-SSL version of the URL (HTTP) it was redirected by the Apache server to a non-valid URL.
Now I have to figure out why Joomla redirects to a HTTP URL and doesn't stay with relative addressing as it is behind a reverse proxy who's handling the SSL part.


text:
Q: Rhapsody - imported library does not exist I am writing a project for school in rhapsody, but I have errors saying that library does not exist. I couldn't find website to download this library, please help me. Maybe you know where download and how install this libraries.
Here's the errors:

*

*error: package com.ibm.rational.rhapsody.animation does not exist.

*error: package com.ibm.rational.rhapsody.oxf does not exist.

*error: package com.ibm.rational.rhapsody.animcom does not exist.

A: These libraries are in the Rhapsody install folder. Try looking here:
C:\Program Files (x86)\IBM\Rational\Rhapsody\8.1.4\Share\LangJava\lib


text:
Q: Callback method setting lightning combobox to previously selected item I have created a text input box and a dependent lightning-combobox. When user inputs acc in text input box, it iterates over a list (fetched from custom obejct in connectedcallback() method) and filters out items which contains acc substring. This filtered list gets displayed in combobox and user selects a item with label Account. When the user clears out the input provided in text box, this filtered list also gets cleared along with the selected item Account.Till here, it is working as expected.
Now,When the user again types in acharacter in text input box, combobox is automatically gets set to previous selected item Account.
I inspected the code and found that the in aura:proddebug.js, below code gets executed and then combobox is getting set to Account. This should not happen and combobox should get cleared out.
for (let i = 0, len = callbacks.length; i < len; i += 1) {
  callbacks[i]();
}

HTML :
<template>
<lightning-card title="Select Report">

        <lightning-input
            name="enter-search"
            label="Search "
            type="text"
            onchange={handleSearchChange}
        ></lightning-input>

        <lightning-combobox
        name="Report List"
        label="Report List"
        value={value}
        placeholder="select report"
        options={reports}
        onchange={handleSelectReportChange}></lightning-combobox>

</lightning-card>
    </template>

JS:
export default class LWCcreateannouncement extends LightningElement {
@api recordId;
@track reportId;
@track reports=[];
@track disableButton = true;
@track error;
allreports=[];

connectedCallback() {
    getReportList()
    .then((result) => {
        this.allreports = result.map((report) => ({ label:report.Name, value:report.Id}));
    })
    .catch((error) => {
        this.error = error;
    });
}

handleSearchChange(event) {
    const allReports = this.allreports;
    const searchTerm = event.target.value;
    if(searchTerm){
        this.reports = allReports.filter(str => {
            return str.label.toLowerCase().includes(searchTerm.toLowerCase());
        });
    } else {
        this.reportId = '';
        this.reports = [];
        this.disableButton = true;
    }

}

handleSelectReportChange(event) {
    this.reportId = event.detail.value;
    if(this.reportId) {
        this.disableButton = false;
    }
}

A: Try chaging the value={value} property of the Combobox with value={reportId}
I think this should solve the problem as you are blanking this.reportId when you clear the search input.


text:
Q: Kubernetes Ingress Controller Fake Certificate on GKE for WSO2 API Management
I encourage an issue regarding setup the TLS Cert-Manager Controller on GKE for WSO2 API Management.

I am using WSO2 product Docker images available from WSO2 Private Docker Registry, following the Helm Chart for the deployment of WSO2 API Manager with WSO2 API Manager Analytics on Github (README). And I successfully deployed the WSO2 API Manager with Nginx Ingress Controller (deploy-a-nginx-ingress-and-a-certitificate-manager-controller-on-gke).

I want to create a Kubernetes cluster on Google Cloud Platform using an Nginx Ingress Controller to integrate with a certificate manager to automate the process of issue and renew the required certificates.

I easily replicate the TLS Cert-Manager Controller on GKE for HelloWorld example from the same medium tutorial (deploy-a-nginx-ingress-and-a-certitificate-manager-controller-on-gke).

hello-app-ingress.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/issuer: letsencrypt-production
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"networking.k8s.io/v1beta1","kind":"Ingress","metadata":{"annotations":{"cert-manager.io/issuer":"letsencrypt-production","kubernetes.io/ingress.class":"nginx","nginx.ingress.kubernetes.io/ssl-redirect":"true"},"name":"hello-app-ingress","namespace":"default"},"spec":{"rules":[{"host":"test.japangly.xyz","http":{"paths":[{"backend":{"serviceName":"hello-app","servicePort":8080},"path":"/helloworld"}]}}],"tls":[{"hosts":["test.japangly.xyz"],"secretName":"test-japangly-xyz-tls"}]}}
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
  creationTimestamp: "2020-08-30T04:27:12Z"
  generation: 3
  name: hello-app-ingress
  namespace: default
  resourceVersion: "6478"
  selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/hello-app-ingress
  uid: ea2d8b13-e9b6-4cb0-873d-76ed40253e4f
spec:
  rules:
  - host: test.japangly.xyz
    http:
      paths:
      - backend:
          serviceName: hello-app
          servicePort: 8080
        path: /helloworld
  tls:
  - hosts:
    - test.japangly.xyz
    secretName: test-japangly-xyz-tls
status:
  loadBalancer:
    ingress:
    - ip: 35.239.145.46

However, not working the WSO2 API Management, all I get is

Kubernetes Ingress Controller Fake Certificate

wso2am-pattern-1-am-ingress.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    cert-manager.io/issuer: letsencrypt-production
    kubernetes.io/ingress.class: nginx
    meta.helm.sh/release-name: wso2am-pattern-1
    meta.helm.sh/release-namespace: wso2-apim
    nginx.ingress.kubernetes.io/affinity: cookie
    nginx.ingress.kubernetes.io/backend-protocol: HTTPS
    nginx.ingress.kubernetes.io/session-cookie-hash: sha1
    nginx.ingress.kubernetes.io/session-cookie-name: route
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
  creationTimestamp: "2020-08-30T04:41:10Z"
  generation: 4
  labels:
    app.kubernetes.io/managed-by: Helm
  name: wso2am-pattern-1-am-ingress
  namespace: wso2-apim
  resourceVersion: "88840"
  selfLink: /apis/extensions/v1beta1/namespaces/wso2-apim/ingresses/wso2am-pattern-1-am-ingress
  uid: 58f4b549-a565-493b-9f9f-72ad76877819
spec:
  rules:
  - host: am.japangly.xyz
    http:
      paths:
      - backend:
          serviceName: wso2am-pattern-1-am-service
          servicePort: 9443
        path: /
  tls:
  - hosts:
    - am.japangly.xyz
    secretName: am-japangly-xyz-tls
status:
  loadBalancer:
    ingress:
    - ip: 35.239.145.46

A: As I said in the comment:

I ran setup like yours and noticed that the cert-manager was creating the secret but was not provisioning it further. Issuer is namespaced resource and needs to be in namespace where your Ingress resides. Please tell if your namespace wso2-apim have the Issuer needed to provide the certificate. For troubleshooting you can run $ kubectl describe certificate -n namespace. Also the fake Kubernetes certificate is used when there is an issue with a tls: secret part.

I wanted to give more insight on what the potential issue may be and some other tips working with nginx-ingress.

Certificate showing as Kubernetes Ingress Controller Fake Certificate will kick in when there are issues with the actual secret storing the certificate used in the Ingress definition.
One of the possible situations where Fake Certificate will kick in is in the lack of the actual secret with a certificate.

As pointed in the part of my comment, Issuer is a namespaced resource and it needs to be in a namespace that Ingress and secret is created. It will create a secret but it will not progress further with signing.
Looking on your setup:

*

*nginx-ingress controller spawned in nginx namespace (GOOD)

*cert-manager spawned in namespace cert-manager namespace (GOOD)

*Issuer for certificates spawned in default namespace (POTENTIAL ISSUE)

*WSO2 application spawned in wso2-apim namespace (POTENTIAL ISSUE)

To make it work you can either:

*

*Run your WSO2 application in default namespace same as Issuer

*Create an Issuer in wso2-apim namespace

*Create a ClusterIssuer
As pointed by official documentation:

An Issuer is a namespaced resource, and it is not possible to issue certificates from an Issuer in a different namespace. This means you will need to create an Issuer in each namespace you wish to obtain Certificates in.
Cert-manager.io: Docs: Concepts: Issuer

As for troubleshooting steps you can invoke following commands:

*

*$ kubectl describe issuer ISSUER_NAME -n namespace

*$ kubectl describe certificate CERTIFICATE_NAME -n namespace

*$ kubectl describe secret SECRET_NAME -n namespace

Assuming that:

*

*You have a working Kubernetes cluster

*You have spawned nginx-ingress and have the LoadBalancer IP provisioned correctly

*You have a domain name pointing to the LoadBalancer IP of your nginx-ingress controller

After that you spawned:

*

*example namespace

*hello-app as in medium guide:

*

*$ kubectl create deployment hello-app --image=gcr.io/google-samples/hello-app:1.0 -n example

*exposed it locally

*

*$ kubectl expose deployment hello-app --type=NodePort --port=8080 -n example

*created an Ingress resource like below:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress
  namespace: example
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/issuer: "letsencrypt-prod"
spec:
  tls:
  - hosts:
    - super.example.com
    secretName: super-example-tls
  rules:
  - host: super.example.com
    http:
      paths:
      - path: /
        backend:
          serviceName: hello-app
          servicePort: 8080

With no Issuer in the example namespace the logs from the certificate will look like that:

*

*$ kubectl describe certificate super-example-tls -n example
Events:
  Type    Reason     Age    From          Message
  ----    ------     ----   ----          -------
  Normal  Issuing    6m33s  cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  6m33s  cert-manager  Stored new private key in temporary Secret resource "super-example-tls-XXXXX"
  Normal  Requested  6m33s  cert-manager  Created new CertificateRequest resource "super-example-tls-XXXXX"

Issuer.yaml used in an example for more reference:
kind: Issuer
metadata:
  name: letsencrypt-prod
  namespace: example
spec:
  acme:
    # The ACME server URL
    server: https://acme-v02.api.letsencrypt.org/directory
    # Email address used for ACME registration
    email: PUT_EMAIL_ADDRESS_HERE
    # Name of a secret used to store the ACME account private key
    privateKeySecretRef:
      name: letsencrypt-prod
    # Enable the HTTP-01 challenge provider
    solvers:
    - http01:
        ingress:
          class: nginx

After you create an Issuer you should see a new event in certificate:
  Normal  Issuing    25s    cert-manager  The certificate has been successfully issued


text:
Q: The simple transition of matrix but what went wrong? #include <stdio.h>

main(){
    int A[3][2] = {0} ;

    printf("A = \n");
    for(int x = 0 ; x < 3 ; x++){
        for (int y = 0 ; y < 2 ; y ++){
            A[x][y] = (x+1)*1 + (x*1+3)*y ;
            printf("A[%d][%d] = %d ", x , y ,A[x][y]);
        }
        printf("\n");
    }
    printf("\nAT = \n");
    for (int p = 0 ; p < 2 ; p++){
        for (int q = 0 ; q < 3 ; q++){
            A[p][q] = A[q][p];
            printf("A[%d][%d] = %d ", p ,q , A[p][q]);
        }
        printf("\n");
    }
}

Why does AT[1][0] = 2 not 4?
I have tested it for an hour for this simple question, but I have no idea.

A: If you transpose a non-square matrix then the dimensions of the resulting matrix will also be transposed. Not only that, if you were going to transpose in-place you would need to swap pairs of elements, otherwise you would be overwriting some of the elements before they had been transposed.
So, to solve both these problems you should probably just use a second matrix with the correct dimensions for the transposed result, e.g.
#include <stdio.h>

int main()
{
    int A[3][2] = {0};
    int AT[2][3] = {0};  // <<<

    printf("A = \n");
    for(int x = 0 ; x < 3 ; x++){
        for (int y = 0 ; y < 2 ; y ++){
            A[x][y] = (x+1)*1 + (x*1+3)*y ;
            printf("A[%d][%d] = %d ", x, y, A[x][y]);
        }
        printf("\n");
    }
    printf("\nAT = \n");
    for (int p = 0 ; p < 2 ; p++){
        for (int q = 0 ; q < 3 ; q++){
            AT[p][q] = A[q][p]; // <<<
            printf("A[%d][%d] = %d ", p, q, AT[p][q]);
        }
        printf("\n");
    }
    return 0;
}

LIVE DEMO

A: You are accessing the array out of bounds when the condition came,
 A[0][2]=A[2][0]; // <--

Here You can access only until first location. So as like Paul R says Use the
separate array when you transpose the array.
For example consider your array is declared in memory like this.
Memory Address     125    126     127     128     129     130
                    ^      ^       ^       ^       ^       ^
                    |      |       |       |       |       |
Array accessing  [0][0]  [0][1]  [1][0]  [1][1]  [2][0]  [2][1]

what will happen when you are accessing the [0][2]. It will go to the [1][0].


text: Q: Is possible to install minifilter drivers on Windows 10 without any certificates? I am developing a Mini Filter Driver for a Ransomware Detection college work. The purpose of it is live testing against malwares, not gonna be sold or anything like that. Considering Drivers needs certificates to run on Windows 10, is there a way where I can install the driver anyways despite not having any certficate ?


text:
Q: How to list all the UTF-8 characters used in a text file that are not part of the ISO 8859-1 charset with PHP? I have a big (900+ MB) SQL (text) file saved in UTF-8. The content of the file is valid and is only UTF-8 (nothing double-encoded or in the wrong charset).
I want to parse this file to find all the UTF-8 characters used in this file that are not part of the ISO 8859-1 charset. As you know a-zA-Z in ISO 8859-1 are the same binary in UTF-8 so I don't want to list them.
It's because I found out that there is some C2 A0 characters (UTF-8 non-breaking spaces) used. I normalized them to regular spaces because 2 different entries had the same text but were different (space and non-breaking space look the same to the user but are different for the database). Now I'm wondering if there are similar problems with other characters (like commas or quotes)?
I want to parse this file to list all the UTF-8 characters that are not present in ISO 8859-1 (Latin1). That way I will only list "special" UTF-8 characters that might be problematic and I will normalize them manually prior the insertion in the new database.
Here is what I would like:
$utf8CharList = array();
$handle = fopen('somefile.sql', 'r');
while (!feof($handle)) {
  $str = fread($handle, $charLenght); /*What would be the correct length? 1 or 2 or variable?*/
  if (charIsOnlyInUTF8($str)) { /*Since "a" is binary the same in UTF-8 and ISO 8859-1 I don't want to list it*/
      if (!in_array($str, $utf8CharList)) {
          $utf8CharList[] = $str;
      }
  }
}
fclose($handle);
print_r($utf8CharList);

A: This is really not a complicated question.
You basically want an Ord() for utf8.  Ascii characters in utf8 have an ordinal value < 127.
However, utf-8 characters > Ord() 255 will be in 2-4 character sequences, so, if reading a utf-8 file byte by byte, you have to know whether or not you are in a multibyte utf-8 character sequence. There are a number of implementations of routines you can use in the comments of the http://php.net/ord page.
Rather than copy them here, I would urge you to determine which of them appeals to you to solve your problem.

A: It would seem to me that you'd want to find any non-ASCII characters, as even "Latin-1 characters" may come in different flavors (composed vs. decomposed for instance; not sure if you care about that, but may be important). Since all ASCII characters are a single byte and all other characters are two or more in UTF-8, this is a pretty trivial operation.
for ($i = 0, $length = mb_strlen($string, 'UTF-8'); $i < $length; $i++) {
    $char = mb_substr($string, $i, 1, 'UTF-8');
    if (strlen($char) > 1) {
        echo 'Found a non-ASCII character: ', $char, ' (', bin2hex($char), ')', PHP_EOL;
    }
}


text:
Q: How to plot color as function of a third variable using matplotlib.scatter? I want to plot Points with x and y-Values and colour them depending on a corresponding time value. Data is stored in a Dataframe.
The solution should be the c-parameter of matplotlib's scatter function, but for some reason its not working for me.
The times-column is a List of float values between 0 and 3.
Plotting the Points without c-parameter is working.
import matplotlib.pyplot as plt

c=list(df_result_local['times'])
for i in range(len(df_result_local['Points'])):
    plt.scatter(df_result_local['Points'][i].x, df_result_local['Points'][i].y, c=c, alpha = 0.5)

Here I get a ValueError: 'c' argument has 1698 elements, which is not acceptable for use with 'x' with size 1, 'y' with size 1.

A: Try this
import matplotlib.pyplot as plt

c=list(df_result_local['times'])
x = []
y = []
for i in range(len(df_result_local['Points'])):
    x.append(df_result_local['Points'][i].x)
    y.append(df_result_local['Points'][i].y)

plt.scatter(df_result_local['Points'][i].x, df_result_local['Points'][i].y, c=c, alpha = 0.5)

A: I think you need to use the index on c as well. So
plt.scatter(df_result_local['Points'][i].x, df_result_local['Points'][i].y, c=c[i], alpha = 0.5)


text:
Q: Conventional way to find all .cpp .h files in a directory (include, src, etc...) I want to extract an example from a large codebase/API, but I would like to avoid using the designated build system, and manually find all the file dependencies into one big folder that I can just g++ *.cpp, and it will "just work". Is there any such method to do this?
main.cpp
project
│
├── src
│   ├── source.cpp
│   └── *.cpp
└── include
    ├── source.h
    └── *.h

A: Ended up writing a small script even though it probably isn't the easiest/most efficient way, it still achieves the result. It is pretty useful just to get a string containing all headers and source files which can be used in conjunction with cp [headers] /path/to/dst to create an simple ad-hoc structure for MVCE, code extraction, prototyping, etc...
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <list>

/*
* Recursively navigates the file tree and finds all .h header files
* and all .cpp files, to be used to "scrape" large codebases
*
*/

std::list<std::string> source_list = {};
std::list<std::string> header_list = {};

int is_dir(const char *path)
{
    struct stat statbuf;
    if (stat(path, &statbuf) != 0)
        return 0;
    return S_ISDIR(statbuf.st_mode);
}

void dirSearch(std::string p)
{
    FILE *fp;
    char path[100];

    std::string cd = "cd ";
    std::string ls = " && ls";
    std::string cmd = cd + p + ls;

    fp = popen(cmd.c_str(), "r");
    if (fp == NULL) {
        printf("Failed to run command\n");
        exit(1);
    }
    while (fgets(path, sizeof(path)-1, fp) != NULL) {

        std::string abs_path = p + "/" + path;

        // rm \n
        abs_path.pop_back();

        // any folder can be a path to search for headers in
        if ( is_dir(abs_path.c_str()) ) {
            dirSearch(abs_path);
        }
        // if not a directory, check if the file is a .cpp file and add to list of source files
        else {
            std::string SOURCE_FILE_EXT = ".cpp";

            if (abs_path.substr(abs_path.size() - SOURCE_FILE_EXT.size(), abs_path.size()) == SOURCE_FILE_EXT) {
                source_list.push_back(abs_path);
            }

            std::string HEADER_FILE_EXT = ".h";

            if (abs_path.substr(abs_path.size() - HEADER_FILE_EXT.size(), abs_path.size()) == HEADER_FILE_EXT) {
                header_list.push_back(abs_path);
            }
        }
    }
    pclose(fp);
}

int main(int argc, char **argv)
{
    dirSearch(argv[1]);

    std::string headers = "";
    std::string fsource = " ";

    // add header path
    for (std::string l : header_list) {
        all_header_files += " " + l;
    }
    // add source files
    for (std::string l : source_list) {
        all_source_files += " " + l;
    }

    std::cout << all_header_files << std::endl;
    std::cout << all_source_files << std::endl;
}

Here is an example usage:
g++ scrape_source.cpp -o scrape_source
./scrape_source PhysX-4.1

... PhysX-4.1/physx/src/fastxml/src/PsFastXml.cpp PhysX-4.1/physx/src/foundation/src/PsAllocator.cpp PhysX-4.1/physx/src/foundation/src/PsAssert.cpp PhysX-4.1/physx/src/foundation/src/PsFoundation.cpp PhysX-4.1/physx/src/foundation/src/PsMathUtils.cpp PhysX-4.1/physx/src/foundation/src/PsString.cpp PhysX-4.1/physx/src/foundation/src/PsTempAllocator.cpp PhysX-4.1/physx/src/foundation/src/PsUtilities.cpp PhysX-4.1/physx/src/foundation/src/unix/PsUnixAtomic.cpp PhysX-4.1/physx/src/foundation/src/unix/PsUnixCpu.cpp PhysX-4.1/physx/src/foundation/src/unix/PsUnixFPU.cpp PhysX-4.1/physx/src/foundation/src/unix/PsUnixMutex.cpp PhysX-4.1/physx/src/foundation/src/unix/PsUnixPrintString.cpp PhysX-4.1/physx/src/foundation/src/unix/PsUnixSList.cpp PhysX-4.1/physx/src/foundation/src/unix/PsUnixSocket.cpp PhysX-4.1/physx/src/foundation/src/unix/PsUnixSync.cpp PhysX-4.1/physx/src/foundation/src/unix/PsUnixThread.cpp PhysX-4.1/physx/src/foundation/src/unix/PsUnixTime.cpp PhysX-4.1/physx/src/foundation/src/windows/PsUWPThread.cpp PhysX-4.1/physx/src/foundation/src/windows/PsWindowsAtomic.cpp PhysX-4.1/physx/src/foundation/src/windows/PsWindowsCpu.cpp ...


text:
Q: console.log in php backend   I did also creating a different class. but still not working...

but if I place the  '<script>console.log("message here");</script>' will work..

//index.html
assuming that this is a complete code.
    <form action="post.php" method="post">
    <input type="text" name="name" id="name"/>
    <input type="submit" value="submit"/>
    </form>

//post.php

    <?PHP
if(isset($_POST['name'])){
        echo "<script>console.log('".$_POST['name']."');</script>";
    }
?>

my problem is , i cant use console.log in submitting a form.  but if I did this in redirection It will work..
The Function under my class is ...
public function console($data) {
  if(is_array($data) || is_object($data)) {
     echo("<script>console.log('".json_encode($data)."');</script>");
  } else {
     echo("<script>console.log('".$data."');</script>");
  }
}

A: It does not work within PHP because of the missing " around the String argument of console.log.
The output would've been
<script>console.log(name);</script>

instead of
<script>console.log("name");</script>

Solution
echo '<script>console.log("'.$_POST['name'].'");</script>';

A: If you are trying to debug or see the value that was posted from the front end to back end then you can simply use the chrome inspector.

*

*Right click anywhere in browser and click inspect element.

*click on network tab.

*submit your form with desired values.

*on the left click on the post.php.

*Click on the headers on the right and scroll down to find Form Data.

*You will have all your post variables listed there with respective values.

A: You seem to be trying to debug the $_POST variable, If thats the case, then Please note, that console.log() is a frontend debugging tool used in javascript, and has nothing to do with php.
Few good way of checking the content of variables in php.
1. print_r
This will output the content of a variable that can be an array, object or string in a nice human readable format.
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();

2. var_dump
This will output the content of the variable with extra respective details  like datatypes and length.
var_dump($_POST);
die();


text:
Q: How to retrieve results without going through scanner - Zxing/Android I'm writing an application that uses the Zxing bar code scanner. I have a button that takes you to a history page in a ListView. When an item in the history list is clicked, i want to be able to view it's results that are usually shown after scanning the bar code. How will i be able to do that?

A: You can't intercept this function of Barcode Scanner and send it to your app, no.


text:
Q: Pushing empty array using useState in React I've been working on an e-commerce website and when i click on an item to get it into the car, i've created a function to push the element into a Car array.
const getItem=(id) =>{
        const product=products.find(item =>
            item.id === id)
            return product;
    }

    const addToCart=(id)=>{
        let tempProducts=[...products]
        const index=tempProducts.indexOf(getItem(id))
        const product=tempProducts[index];
        product.inCart=true;
        product.count=1;
        const price=product.price;
        product.total=price;
        setCart([...cart,product]);
        setProductos(tempProducts);
        console.log(cart)
    }

The problem that i got is when i clicked to the first element to go into the Cart array it pushes an empty value, but when i clicked the second item, it brings me the previous array that i clicked.
I don't know what happens with the index but if you know about it, please tell me


text:
Q: How to add imports to default export in TypeScript I have this TypeScript node module that imports some base errors (errors1 and errors2) and define some module specific errors3:
// in errors3.ts
import errors1 from './errors1'
import errors2 from './errors2'

const errors3 = {
  ...
}

export default ? // <-- want to merge and export all errors here

Is there a way to combine all 3 error objects into one default export without explicit merging these objects into one manually (i.e. via Object.assign, lodash, etc?

A: You can use a barrel to export them all and then import them under a namespace.
https://basarat.gitbooks.io/typescript/docs/tips/barrel.html


text:
Q: Is "equal to none" a fixed phrase? I encountered this as a phrase in

Trent Hawkins is a skilled pilot and war veteran, whose piloting skill are equal to none

and it seems a bit strange. Is this an actual phrase or has the author of this sentence botched this up?

A: An idiomatic way to say this is with the phrase "second to none"

Trent Hawkins is a skilled pilot and war veteran, whose piloting skill
  is second to none.

It means that nobody is better than Trent.


text:
Q: Devise - Redirected to page if account isn't confirmed I'm trying to redirect the user if their account hasn't been confirmed. So this involves two parts of the code:

*

*Redirect the user after they first create the account

*Redirect them if they try to sign in before confirming the account

I need help with the second.
The first I was able to do by putting in after_inactive_sign_up_path_for(resource) in my custom RegistrationsController. I've tried to do the same for a SessionsController, but it didn't work. What do I need to over write in order to properly redirect the user if they haven't confirmed the account yet?

A: You may have to create a custom warden strategy and check if the account needs confirmation. Something of this sorts:
# config/initializers/my_strategy.rb
Warden::Strategies.add(:my_strategy) do
  def valid?
    true
  end

  def authenticate!
    u = User.find_for_authentication(:email => params[:email])
    if u.nil? || !u.valid_password?(params[:password])
      fail(:invalid)
    elsif !u.confirmed?
      fail!("Account needs confirmation.")
      redirect!("your_root_url")
    end
  else
    success!(u)
  end
end

#config/initializers/devise.rb
config.warden do |manager|
  manager.default_strategies(:scope => :user).unshift :my_strategy
end

This assumes the username and password are passed in the request as params. You can look at the database_authenticable strategy for an example of how Devise deals with sign-in authentication by default.


text:
Q: OR condition in java substring method While parsing the dynamic input string using the java substring method with start and end indexes, Can we use or condition in the end index of the substring method? Meaning end index could be either ')' or ',' for my use case.
Ex: my input string have below two formats
inputformat1 : Student(name: Joe, Batch ID: 23) is updated
inputformat2 : Student(name: John, ID:0, Batch ID: 2503, Result: pass) is updated

Now I am interested to get the "Batch ID" value every-time. I wanted to achieve this by substring method. Now I'm able to get the batch id value If I use any one of the indexes i.e, ')' or ','
String batchId= input.substring(input.indexOf("Batch ID: ")+9,input.indexOf(")"));

Can someone help me to the way to batch Id value basing on different end indexes?

A: You could use Math.min():
String batchId = input.substring(input.indexOf("Batch ID: ") + 9,
                     Math.min(tail_old.indexOf(")"), tail_old.indexOf(",")));

A: You can use regex with replaceFirst to solve your problem for example ;
List<String> strings = Arrays.asList("Student(name: Joe, Batch ID: 23) is updated",
        "Student(name: John, ID:0, Batch ID: 2503, Result: pass) is updated"
);
for (String string : strings) {
    System.out.println(
            string.replaceFirst(".*Batch ID:\\s+(\\d+).*", "$1")
    );
}

Outputs
23
2503

If you want multiple groups you can also use Patterns like so :
Pattern pattern = Pattern.compile("name:\\s+(.*?),.*?Batch ID:\\s+(\\d+)");
Matcher matcher;
for (String string : strings) {
    matcher = pattern.matcher(string);
    while (matcher.find()) {
        System.out.println(
                String.format("name : %s, age : %s", matcher.group(1), matcher.group(2))
        );
    }
}

Outputs
name : Joe, age : 23
name : John, age : 2503


text:
Q: Create playable videostream from bytes/frames Java/Android I have org.webrtc.VideoFrame frames stream.
The frames are coming one by one.
Is there any lib or tool to convert frames to stream on a fly?
I could successfully take convert that VideoFrames to array of bytes.
(similar as this question that uses it for image)
Android org.webrtc.VideoRenderer.I420Frame arrays to PreviewCallback.onPreviewFrame byte[]
I would like to create playable stream video but when I try to play the one create with FileOutputStream or any other stream that can be passed to FFMPEG for example it is not playable, so seems it needs muxer to create it?
private fun addMetaDataToVideo() {
   val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DCIM).toString() + "/"
   +"KYR", "${videoNamePrefix}}.mp4")
   val out = FileOutputStream(file)
   listOfFrames.forEach { out.write(it) }
   out.close()
   addMetaDataToVideo(file)
}

   private fun addMetaDataToVideo(videoFile: File) {
       val values = ContentValues(3)
       values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
      // values.put(MediaStore.Video.Media.DURATION, getVideoDuration(videoFile))
       values.put(MediaStore.Video.Media.DATA, videoFile.absolutePath)
       context.contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values)
   }

A: Using ffmpeg is the most common way to do it.
Can you put your frames into some sort of image aray? BufferedImage or something like it? Once you have your images you can use the following line. Like explained here: https://hamelot.io/visualization/using-ffmpeg-to-convert-a-set-of-images-into-a-video/
Try to write your frames into a BufferedImage,
ffmpeg -r 60 -f image2 -s 1920x1080 -i pic%04d.png -vcodec libx264 -crf 25  -pix_fmt yuv420p test.mp4


text:
Q: Installing dependencies with Qmake using INSTALLS variable I have a project and I am using following lines to move an xml file to my executable directory.
xmls_to_move.path = $${OUTDIR}
xmls_to_move.files = somefile.xml
INSTALLS += xmls_to_move

I can check that qmake sees the file, CTRL and clicking it navigates to it. But for some reason, it does not move the file after build. What might be the reason?

A: You need to run INSTALL as make target: make install.
If you want it to be run automatically you can add it as custom build step, as described here.


text:
Q: mapView:viewForOverlay: not getting called I have a view controller for my Map View.  Inside the viewDidLoad method, I'm setting the mapview's delegate to the controller (self) and then I'm adding the MKOverlay object.  But my mapView:viewForOverlay: method is not getting called, so I still can't get anything to display on my map.
Thanks

A: Chances are you haven't set up the coordinate or boundingMapRect properties on the MKOverlay correctly. The MapView will only ask for the view if it thinks there is a possibility that it is visible, if its visible rect doesn't intersect the boundMapRect, it won't.


text:
Q: MySql - combine REGEXP and BETWEEN functions I have this table.

+--------+----------------+
| id     | e_id           |
+--------+----------------+
| 164462 | " 3 1 2 4 6 "   |
| 164463 | " 185 1 2 4 6 " |
| 164464 | " 3 1 2 1140 6 "|
| 164465 | " 52 1 2 4 6 "  |
| 164466 | " 3 1 175 4 6 " |
| 164467 | " 3 1 2 4 6 "   |
| 164468 | " 3 1 2 4 6 "   |
| 164469 | " 3 1 2500 4 6 "|
| 164470 | " 82 1 2 4 6 "  |
| 164471 | " 3 1 2 4 6 "   |
| 164472 | " 3 1 50 4 6 "  |
| 164473 | " 3 1 2 4 6 "   |
+--------+-----------------+
I must find that rows that contains numbers between 175 and 2574, but numbers are separated just with [[:space:]].
I was tried to use mysql query like this:
 select *
   from table_name
   where e_id between REGEXP '[[:space:]]175[[:space:]]'
     and  REGEXP '[[:space:]]2574[[:space:]]';

...and a lot of combination like this one, but no luck...
Thanks For Help!:)

A: You should never have this kind of "list" in a single database column. In this case, you should have another table to link one e_id at a time.
Anyway, this is a solution to your problem if boundaries aren't dynamic : create a regex to match every number between 175 and 2574 :
SELECT *
FROM table_name
WHERE e_id REGEXP("[[:space:]](1(7[5-9]|[89]\d)|[2-9]\d{2}|1\d{3}|2([0-4]\d{2}|5[0-6]\d|57[0-4]))[[:space:]]")

Regex details :

*

*1(7[5-9]|[89]\d) will match 175 to 199

*[2-9]\d{2} will match 200 to 999

*1\d{3} will match 1000 to 1999

*2([0-4]\d{2}will match 2000 to 2499

*25[0-6]\d will match 2500 to 2699

*257[0-4] will match 2570 to 2574

This solution is ugly, because your database is ugly.
It works for specific boundaries, but as you can see you'll need to rewrite another regex if you change these boundaries.

What you should have:
A table with your ids, another one with "e_ids", and then a third one to link both first :
CREATE TABLE `elements` (
    `id` INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (`id`)
);
CREATE TABLE `other_elements` (
    `e_id` INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (`e_id`)
);
CREATE TABLE `link_table` (
    `id` INT NOT NULL,
    `e_id` INT NOT NULL,
    INDEX `id` (`id`),
    INDEX `e_id` (`e_id`),
    CONSTRAINT `FK__elements`
        FOREIGN KEY (`id`)
        REFERENCES `elements` (`id`)
        ON UPDATE CASCADE
        ON DELETE CASCADE,
    CONSTRAINT `FK__other_elements`
        FOREIGN KEY (`e_id`)
        REFERENCES `other_elements` (`e_id`)
        ON UPDATE CASCADE
        ON DELETE CASCADE
);

You then will be able to get what you want easily :
SELECT *
FROM elements e
JOIN link_table l
  ON l.id = e.id
WHERE l.e_id BETWEEN 175 AND 2574


text:
Q: How to design a database idempotent microservice (POST) This is a very general and basic question regarding how to design a POST database service (new to implementing microservice). Say you have a SaveCustomer microservice. You so a POST to pass the customer data, and the SaveCustomer service receives the data (JSON) and inserts it into the database.
Due to network congestion etc, the client might retry and send duplicate requests, so how do you ensure that you dont insert duplicate records in the database?
Thanks
Obaid

A: Although POST is not idempotent you could implement this by assigning each command a unique ID, for example a GUID. Then, on the microservice, before you execute a command, you check that the command was not processed already. If it was, then you ignore it otherwise you send it to the real component that do the real update and mark the command as executed.
This solution is elegant as it can be implemented as an additional component that can decorate the core logic, following the Open/close principle and Single responsibility principle. Additionally, you can use the Dependency injection root configuration to use or not this idem-potency protection.


text:
Q: Safely bind method from one class to another class in Python I know I can attach a function to a class and make it a method:
 >>> def is_not_bound(inst, name):
...     print("Hello %s" % name)
...
>>>
>>> class NoMethods:
...     pass
...
>>>
>>> setattr(NoMethods, 'bound', is_not_bound)
>>>
>>> NoMethods().bound("oz") # prints: Hello oz
Hello oz

To my surprise this works also with a bound method from one class to another:
>>> class Foo:
...     def foo(self, name):
...         print("Hello %s" % name)
...
>>> class B:
...     pass
...
>>> setattr(B, 'bound_to_b', getattr(Foo, 'foo'))
>>> B().bound_to_b("confused?")
Hello confused?
>>>

Can I safely use this? Is there something I am overseeing?
update
One caveat that I found already:
>>> B.bound_to_b
<function Foo.foo at 0x7fc997e8b730>

Even though I called the method from B, It seems bound to Foo.
And even more surprising!:
>>> def new_method(self, addto):
...     return self.num + addto
...
>>> setattr(B, 'add', new_method)
>>> b=B()
>>> b.num = 2
>>> b.add(2)
4

A: Apparently, this is an intended behavior (which is cool!). But also apparently, this behavior is not very familiar.
If you knew Python 2 for a long time, you would might not be aware of the fact that Python 3 has no methods (as commented above).
So in Python 3:
>>> class Foo:
...     def foo(self, name):
...         print("Hello %s" % name)
...
>>> Foo.foo
<function Foo.foo at 0x7f729a406730>
>>> def foo():
...     pass
...
>>> foo
<function foo at 0x7f729b83ff28>
>>>
>>> Foo.foo
<function Foo.foo at 0x7f729a406730>

There is no distinction! In Python 2 however:
Python 2.7.14 (default, Feb  2 2018, 02:17:12)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def foo(self, name):
...         print("Hello %s" % name)
...
>>> Foo.foo
<unbound method Foo.foo>
>>>