text:
Q: Application crashes when pressing the button I have struggled to find the solution for couple of days and it has drive me nuts. I am currently following the tutorial in http://developer.android.com/guide/topics/ui/actionbar.html#ActionItems
Unfortunately the application crashes when SEND button was pressed (It was working fine before the action bar was implemented)

Here are the involved files:

1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mycompany.myfirstapps" >
    <uses-sdk android:minSdkVersion="7"
    android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar">

        <!-- parent activity-->
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <!--second activity -->
        <activity
            android:name=".DisplayMessageActivity"
            android:label="@string/title_activity_display_message"
            android:parentActivityName=".MyActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MyActivity" />
        </activity>

    </application>

</manifest>

*MyActivity.java

package com.mycompany.myfirstapps;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.content.Intent;
import android.widget.EditText;

public class MyActivity extends AppCompatActivity {
    public final static String EXTRA_MESSAGE="com.mycompany.myfirstapps.MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // If your minSdkVersion is 11 or higher, instead use:
        //getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_search:
                openSearch();
                return true;
            case R.id.action_settings:
                openSettings();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    //called when user click the button
    public void sendMessage(View view){
        Intent intent = new Intent(this,DisplayMessageActivity.class);
        EditText editText=(EditText)findViewById(R.id.edit_message);
        String message=editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE,message);
        startActivity(intent);
    }

    private void openSearch() {
     //do something
    }

    private void openSettings() {
//do something
    }

}

*DisplayMessageActivity.java

package com.mycompany.myfirstapps;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

    public class DisplayMessageActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent= getIntent();

        //create the text view
        String message=intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
        TextView textview= new TextView(this);
        textview.setTextSize(40);
        textview.setText(message);

        //set the text view as the activity layout
        setContentView(textview);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_display_message, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

*activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:theme="@style/CustomActionBarTheme">

<EditText
    android:id="@+id/edit_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/edit_message"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage"/>

</LinearLayout>

*build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.mycompany.myfirstapps"
        minSdkVersion 8
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
}

Logcat
05-14 22:57:03.139    2514-2562/android.process.acore I/ContactLocale﹕ AddressBook Labels [en-US]: [, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Α, Β, Γ, Δ, Ε, Ζ, Η, Θ, Ι, Κ, Λ, Μ, Ν, Ξ, Ο, Π, Ρ, Σ, Τ, Υ, Φ, Χ, Ψ, Ω, , А, Б, В, Г, Д, Ђ, Е, Є, Ж, З, И, І, Ї, Й, Ј, К, Л, Љ, М, Н, Њ, О, П, Р, С, Т, Ћ, У, Ф, Х, Ц, Ч, Џ, Ш, Щ, Ю, Я, , א, ב, ג, ד, ה, ו, ז, ח, ט, י, כ, ל, מ, נ, ס, ע, פ, צ, ק, ר, ש, ת, , ا, ب, ت, ث, ج, ح, خ, د, ذ, ر, ز, س, ش, ص, ض, ط, ظ, ع, غ, ف, ق, ك, ل, م, ن, ه, و, ي, , ก, ข, ฃ, ค, ฅ, ฆ, ง, จ, ฉ, ช, ซ, ฌ, ญ, ฎ, ฏ, ฐ, ฑ, ฒ, ณ, ด, ต, ถ, ท, ธ, น, บ, ป, ผ, ฝ, พ, ฟ, ภ, ม, ย, ร, ฤ, ล, ฦ, ว, ศ, ษ, ส, ห, ฬ, อ, ฮ, , ㄱ, ㄴ, ㄷ, ㄹ, ㅁ, ㅂ, ㅅ, ㅇ, ㅈ, ㅊ, ㅋ, ㅌ, ㅍ, ㅎ, , あ, か, さ, た, な, は, ま, や, ら, わ, #, ]
05-14 22:57:05.181    2514-2532/android.process.acore V/BackupServiceBinder﹕ doBackup() invoked
05-14 22:57:05.508    2514-2532/android.process.acore I/art﹕ WaitForGcToComplete blocked for 267.334ms for cause DisableMovingGc
05-14 22:57:05.619    2514-2532/android.process.acore E/DictionaryBackupAgent﹕ Couldn't read from the cursor
05-14 22:57:05.722    2514-2562/android.process.acore I/art﹕ WaitForGcToComplete blocked for 357.236ms for cause DisableMovingGc
05-15 01:35:32.770    2514-2525/android.process.acore W/art﹕ Suspending all threads took: 57.246ms
05-15 01:35:35.813    2514-2527/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'close' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
            at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:57)
            at android.os.Binder.execTransact(Binder.java:446)
05-15 01:35:35.925    2514-2527/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'close' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
            at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:64)
            at android.os.Binder.execTransact(Binder.java:446)
05-15 01:35:36.578    2514-2527/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'close' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
            at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:71)
            at android.os.Binder.execTransact(Binder.java:446)

What could be wrong?

A: Move your EditText inside of your onCreate() method in MyActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    EditText editText=(EditText)findViewById(R.id.edit_message);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // If your minSdkVersion is 11 or higher, instead use:
    //getActionBar().setDisplayHomeAsUpEnabled(true);
}

And inside your sendMessage() method, just remove that line.
Edit: It seems like you're extending from the new AppCompatActivity. Try changing it to ActionBarActivity in both the activities. For example:
public class MyActivity extends ActionBarActivity {...}
public class DisplayMessageActivity extends ActionBarActivity {...}

Edit: If you're planning on not using the ActionBarActivity, then you need to define a custom Toolbar and initialze it like this..
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

A: Finally I manage to get the solution after struggling for almost 3 days. the process to resolve this issue is really a journey for me as a newbie in android.
This is list of errors and warning tracked and solved during the process:

*

*The class name ActionBarActivity was strikeout in
public class MyActivity extends ActionBarActivity
The explanation is:
Since the version 22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity

once I clear all the deprecated issue , the next error:

*java.lang.NullPointerException
I solved this issue ( or at least I thought so) by checking the null value
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

*Next error was always pointing to the sendMessage(View view)
I  found this post :
java.lang.IllegalStateExeception: could not find method in activity class
And it solved my problem. My actual mistake was I have set the theme in AndroidManifest.xml and again i set the them in layout file. Causing the application to crash. I removed the one in layout.xml file.


text:
Q: wget fails to perform in a for loop I want to iterate through a list of url's (linking to pictures) and perform a wget to download those pictures.
But the url's are between quotation marks.
I initially put a $ sign in front of the picture variables. It works in a colab notebook, I can actually download the pictures this way in my notebook, but it does not work when I launch the script via my Windows command.
for follower in tweepy.Cursor(api.get_followers, screen_name='@'+screen_name, wait_on_rate_limit=True, count=200).items(9000):
  followers_profile_pic.append(follower.profile_image_url_https)
  for pic in followers_profile_pic:
    pic_id = re.search(pattern, pic).group(1)
    big_pic = f"https://pbs.twimg.com/profile_images/{pic_id}_400x400.jpg"

  quality_pic.append(big_pic)
  for picture in quality_pic:
    wget picture

A:
can actually download the pictures this way in my notebook, but it
does not work when I launch the script via my Windows command.

If portability is concern to you then it is wise to limit to standard library if feasible. There is function specially designed for downloading files - namely urllib.request.urlretrieve. Most basic usage is to provide URL and filename, for example:
import urllib.request
urllib.request.urlretrieve("https://www.example.com","index.html")

urllib.request is part of standard library so generally it should be sufficent to have python installed, unlike external modules, e.g. requests which need separate installation. If you want to know more about urllib.request.urlretrieve read linked docs.

redpajama_set_name: RedPajamaStackExchange


text: Q: Migrate oracle data to user where partition enabled We have a oracle database user which has old data set from 2017. This is a test database. This schema has daily partitions. Recently we find out database actually does not have partitioned scripts ran. Now we stuck with our test database which does not have daily partitions and we cannot do testing which involves in partitions.  Now we want to either enable partitions for old data or create database with partitions and migrate data. Our requirement is to get test database with enough data with partitions enabled. Is there a way we can create new user with partitioned enabled for relevant tables, then migrate our old database ( which has sufficient data set from 2017 ) ? Will migration put those old data to relevant partitions ? Anyone with similar situation ?


text:
Q: asp:textbox calling asp:button handler on text change I have the most bizarre problem happening ... I'm controlling a menu edit page and I have a series of controls, an asp:textbox with the numeric ID of the menu being worked on, flanked by - and + buttons to decrement and increment the ID.  The user can type a new index in the textbox, or use the buttons.  Easy peasy, right?
Here's the ASPX markup:
<asp:Button id="menuDown" runat="server" CausesValidation="false" OnClick="DownClick" Text="-" />
Menu # <asp:textbox runat="server" MaxLength="5" Columns="3" id="tbMenuId" />
<asp:Button id="menuUp" runat="server" CausesValidation="false" OnClick="UpClick" Text="+" />

There's a CompareValidator further down the page ensuring a non-negative, numeric entry.
Over in my code behind, my Page_Load pulls the value out of the textbox without problems:
Try
   menuId = Integer.Parse(tbMenuId.Text)
Catch
   menuId = 0
   tbMenuId.Text = "0"
End Try

This works great (with ONE caveat) — every time I change the menu ID via the textbox, after the Page_Load method pulls the new value out of the text box perfectly, the DownClick handler gets called, decrementing the desired ID.
So far, the ONLY way I've managed to have the requested menu appear is to eliminate the two asp:Button controls. Eliminating only the menuDown button causes the UpClick handler to get called.
I had an OnTextChanged="..." attribute on the asp:Textbox control, but that handler NEVER got called and didn't seem necessary anyway, so I pulled it.
I cannot help but think the two behaviors must be connected.
Anyone understand WHY this is happening?

A: This qualifies as hacky work-around, rather than a fix, but it does let me proceed forward until this behavior can be explained.
The OnTextChanged event is firing the way it's supposed to now (not sure what I did wrong the first time) so, I used it to implement the hackiest of hacks ...
Protected Property hackyFlag As Boolean ' Suppress button click (true) after text change

' ... value in session variable
Protected Sub tbMenuId_TextChanged(sender As Object, e As EventArgs)
    Integer.TryParse(tbMenuId.Text, menuId)
    hackyFlag = True
End Sub

Protected Sub DownClick(sender As Object, e As EventArgs)
    If hackyFlag Then : hackyFlag = False : Return : End If
    If menuId > 0 Then menuId -= 1
    tbMenuId.Text = menuId
End Sub

Gross, hacky, and disgusting ... but it works.  :-)  The button handler is still being called incorrectly, but now it's smart enough to do what I want instead of what the framework is telling it to do.
Still open to better answers and/or explanations as to why this is happening on this page and hasn't happened on any other. ( knock on wood )


text:
Q: Rails view/controller testing with rspec best practices For controller tests, Rails recommends to check for things like HTTP response, authentication, assigns, session and flash messages. However in the app I'm working with right now I see a lot of Rspec tests with response.body.should have_tag(), which, as far as I can tell, would ideally be suited for view tests.
What I'm wondering about is:
Is there any considerable performance/other-kind-of penalty related to such unideal way of testing?

A: If you are rendering views in your controller this will make your controller tests take more time. It all depends on whether you think it's worthwhile to test for the presence of view elements (which tends to make your tests more brittle). If you do, then doing it in the controller specs makes it easier since you don't have to write out a separate view spec file.
If you want to test a lot of things on your views, then you'll probably want to write the separate view specs. Separating out view specs will probably make the overall time for your test suite to run increase. However, for debugging purposes, it'll be clear whether something is wrong in a view vs. a controller with things separated out.
I suspect most Rails programmers don't write view specs. Instead they are probably relying on their integration tests (Capybara +/- Cucumber) to test their views. However integration tests take more time than unit tests. The RSpec book gives the following argument for writing separate view specs:

View specs provide us with an opportunity to discover APIs that we need from the controllers and models. This is not that valuable when the APIs are following the most standard conventions. The value increases, however, as we stray from them....
The only way to really get a feel for the benefits of them [view tests] is to learn to write them well. And only once you really understand how they fit in the flow are you going to be able to make well-grounded decisions about if and when to use them.


text:
Q: Countdown to certain date and adding x hours Timer Main

    $curDate = date("Y-m-d H:i:s", strtotime("-8 hours"));

    $timecountdownend = strtotime($curDate) + strtotime("+1 hours");
    $timecountdownstart = strtotime("-8 hour");
    $timeleft = $timecountdownend - $timecountdownstart;

    if (isset($_POST['type']) && $_POST['type'] == "timerupdate") {
        echo $timeleft;
    }
?>

Timer Update 5 Seconds
$(document).ready(function(){
    var timerText = $("[timer]");

    setInterval(function(){
        $.post("timer.php", {type: "timerupdate"}, function(data){
            timerText.html("Time Left:" + data + " seconds timer.")
        });
    }, 5000);
});

WHAT ARE YOU TRYING TO ACHIEVE?
The idea is when a user reserves an item, expiration date is set into the database so that the USER that reserved the item cannot hold it forever. So for example:

User A: Reserve Item A.
  [SERVER] $database->insert("reservation", $curDate);
  [SERVER] 2016-04-03 16:00:00 (After 30 minutes this item is expired)

That what's supposed to happen in the back-end.
WHAT HAVE YOU TRIED?
I've done tons of googling to see how I could add x hours or minutes to the current date and pass that on to become a unix timestamp.

WHAT IS YOUR PROBLEM?
Whenever I try the code above it works but doesn't come up with the right output I need. Specifically the problem is at $timecountdownend = strtotime($curDate) + strtotime("+1 hours");
** NEW **
date_default_timezone_get("America/New York");

$curDate = date("Y-m-d H:i:s", strtotime("-8 hours"));
$date = new DateTime($curDate);
date_add($date, date_interval_create_from_date_string('2 hour'));

$timecountdownend = strtotime($date->format('Y-m-d H:i:s'));
$timecountdownstart = strtotime("-8 hour");
$timeleft = $timecountdownend - $timecountdownstart;

if (isset($_POST['type']) && $_POST['type'] == "timerupdate") {
    echo $timeleft;
}

OUTPUT: 7200 seconds (STUCK though). It's precise but it's not counting down.

A: Did you consider http://php.net/manual/en/datetime.add.php ?
the only tricky part is to understand how this syntax work : $date->add(new DateInterval('P7Y5M4DT4H3M2S')); P7 means add 7 years H3 means add 3 hours
Once you save or update the date in your database, send a copy along with the response and in your final response document put this :
https://jsfiddle.net/o740okn4/5/
You will need to make these calls from CDN or get the scripts from git
moment.min.js
moment-duration-format.min.js

https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js
and
https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js


text:
Q: What is an alternative to using 'eval' to accessing a variable by name to "sync" it with another? I want to keep two JavaScript variables in sync when I run a function. The variable that is to be pointed to is in an object. The code I have so far is this:
var myname = "bob";
var thevar = "";
var varobj = {tvar: "myname"};
var syncvar = function() {
    thevar = eval(varobj.tvar);
};

syncvar();
alert(thevar); // bob
myname = "eve";
syncvar();
alert(thevar); // eve

How can I do something similar to this without using the dreaded eval? Keep in mind that I want this function to be universal i.e. I want it to work with anyone's objects.
Thanks in advance.
Clarification edit: This is client side. I essentially want a variable that is a "pointer" to another variable (maybe not in the strict definition sense). I have made a function which can sync the variables, but it uses eval, which makes me skeptical. The "universal" part is that I can make tvar point to anything which will sync it. For example, if you include the above code, you can then:
myage = 20;
varobj = {tvar: "myage"};
syncvar();
alert(thevar); // 20
myage = 100;
syncvar();
alert(thevar); // 100

Thus making it "universal" as varobj.tvar can "point" to anything to keep it in sync.

A: You can use setters and getters to make a "virtual" property on the window named thevar, which mirrors to varobj.tvar:
Object.defineProperty(window, 'thevar', {
    get: function( ) { return window[varobj.tvar]    ; },
    set: function(v) {        window[varobj.tvar] = v; }
});

> varobj = { tvar: "bob" }
> thevar = 1
> bob
< 1

Whether or not you really want to do that is another question entirely.


text:
Q: Making Agda reduce an expression in a goal type Using ℕ and _≟_ from the standard library, I have
open import Data.Nat
open import Relation.Binary.PropositionalEquality
open import Relation.Nullary

foo : ℕ -> ℕ -> ℕ
foo x y with x ≟ y
foo x .x | yes refl = x
foo x y  | no contra = y

data Bar : ℕ -> Set where
  bar : (x : ℕ) -> Bar (foo x x)

I want to implement
mkBar : (x : ℕ) -> Bar x
mkBar x = bar x

Agda complains,
Type mismatch:
expected: x
  actual: foo x x | x ≟ x
when checking that the expression bar x
has type Bar x

This makes sense to me: Agda doesn't know a priori that x ≟ x always evaluates to yes refl, so it's not going to evaluate foo x x until it knows a bit more about x.
So I tried rewriting the goal to force x ≟ x to resolve to yes refl,
eq-refl : forall x -> (x ≟ x) ≡ yes refl
eq-refl x with x ≟ x
eq-refl x | yes refl = refl
eq-refl x | no contra = ⊥-elim (contra refl)

mkBar : (x : ℕ) -> Bar x
mkBar x rewrite eq-refl x = bar x

but to no avail. Same error message. I also tried rewriting by foo x x ≡ x:
foo-eq : forall x -> foo x x ≡ x
foo-eq x rewrite eq-refl x = refl

mkBar : (x : ℕ) -> Bar x
mkBar x rewrite foo-eq x = bar x

This answer suggests pattern matching on x ≟ x on the left hand side of mkBar, but it also seems to have no effect:
mkBar : (x : ℕ) -> Bar x
mkBar x with x ≟ x
mkBar x | yes refl = bar x
mkBar x | no contra = ⊥-elim (contra refl)

I must be missing a trick here. How do I get rid of the | in the goal type and make foo x x reduce to x? (I'd prefer not to examine x directly in the LHS of mkBar.)

A: You were almost there: the important thing to notice is that rewrite takes an x ≡ y and replaces x by y in the goal. foo-eq x has type foo x x ≡ x but there is no foo x x to replace in the goal!
What you need to do is rewrite by sym (foo-eq x) like so:
mkBar : (x : ℕ) → Bar x
mkBar x rewrite sym (foo-eq x) = bar x

Bar x then becomes Bar (foo x x) meaning you can apply your constructor.


text:
Q: Multiplicar valor de inputs dinâmicos Tenho uma tabela que gera linhas ao clicar em um botão. Nessas linhas tem dois inputs (amount e price) que preciso pegar os valores inseridos, multiplicar e o resultado exibir em uma coluna de total quando o usuario clicar fora do input estando os dois preenchidos. Não estou sabendo como fazer essa multiplicação e exibir o resultado.

        Produto/Serviço
        Quantidade
        Valor Unitário
        Valor Total
        Remover

            <button class="btn btn-info waves-effect w-md waves-light m-b-5" onclick="AddTableRow()" type="button">Adicionar Produto</button>

Script

A: Neste exemplo o resultado é formatado para o padrão pt-BR com duas casas decimais

$(document).ready(function () {
    var contador = 1;
    //adiciona nova linha
    $("#addLinha").on("click", function () {
        contador++;

        var newRow = $("
");
        var cols = "";
        cols += '<input type="text" name="produto' + contador + '"/>	';
        cols += '<input type="text" name="preco' + contador + '"/>	';
        cols += '<input type="text" name="quant' + contador + '"/>	';
        cols += 'R$ 100,00	';
        cols += ' Excluir 	';
        newRow.append(cols);

        $("#products-table").append(newRow);
    });

    //chamada da função para calcular o total de cada linha
    $("#products-table").on("blur keyup", 'input[name^="preco"], input[name^="quant"]', function (event) {
        calculateRow($(this).closest("tr"));
    });

    //remove linha
    $("#products-table").on("click", "a.deleteLinha", function (event) {
        $(this).closest("tr").remove();
    });
});

//função para calcular o total de cada linha
function calculateRow(row) {
    var preco = +row.find('input[name^="preco"]').val();
    var quant = +row.find('input[name^="quant"]').val();
    //2 casas decimais
    var tot = (preco * quant).toFixed(2);
    //substitui ponto por virgula
    tot=tot.replace(".", ",");
    //a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
    row.find('.total').html("R$ " + (tot).replace(/\B(?=(\d{3})+(?!\d))/g, "."));
}
.deleteLinha {
   color:blue;
   cursor: pointer;
}

      Produto/Serviço
      Quantidade
      Valor Unitário
      Valor Total

        <button class="btn btn-info waves-effect w-md waves-light m-b-5"  id="addLinha" type="button">Adicionar Produto</button>

A: Para responder a essa lógica pode-se criar uma função para os dois eventos, o de blur (clicar fora) e keyup no momento em que se adiciona uma nova linha, e para os elementos adicionados. Essa função apenas tem que navegar no html da linha construída para ir buscar o amount e price com base na função find e fazer os cálculos apropriados:
$(".amount, .price").on("blur keyup",function(){ //register o evento de blur e keyup
    const tr = $(this).parent().parent(); //andar dois elementos para cima até ao

    const quant = parseInt(tr.find('.amount').val()); //ir buscar a quantidade com base no

    const valor = parseInt(tr.find('.price').val()); //ir buscar o valor com base no

    if (!isNaN(quant) && !isNaN(valor)){ //ver se ambos existem
      tr.find('.total').html("R$ " + (quant * valor)); //aplicar o calculo no total
    }
});

Desta forma as funções que antes existiam para cálculo dos totais já não são necessárias.
Colocando tudo a funcionar:

RemoveTableRow = function(handler) {
  var tr = $(handler).closest('tr');
  tr.fadeOut(400, function() {
    tr.remove();
  });
  return false;
};

AddTableRow = function() {

  var newRow = $("
");
  var cols = "";

  cols += '<input type="text" class="form-control product" name="product[]">	';
  cols += '<input type="text" class="form-control amount" name="amount[]">	';
  cols += '<input type="text" class="form-control price" name="price[]">	';
  cols += 'R$ 100,00	';
  cols += '';
  cols += '';
  cols += '	';

  newRow.append(cols);
  $("#products-table").append(newRow);

  $(".amount, .price").unbind('blur keyup');
  $(".amount, .price").on("blur keyup",function(){
    const tr = $(this).parent().parent();

    const quant = parseInt(tr.find('.amount').val());
    const valor = parseInt(tr.find('.price').val());

    if (!isNaN(quant) && !isNaN(valor)){
      tr.find('.total').html("R$ " + (quant * valor));
    }
  });

  return false;
};

      Produto/Serviço
      Quantidade
      Valor Unitário
      Valor Total
      Remover

        <button class="btn btn-info waves-effect w-md waves-light m-b-5" onclick="AddTableRow()" type="button">Adicionar Produto</button>


text:
Q: TfIdfVectorizer not tokenizing properly As far as I'm concerned, there is no question like this. I'm working on a NLP and sentiment analysis project in Kaggle and first of all I'm preparing my data.
The dataframe is a text column followed by a number from 0 to 9 which categorizes which cluster does the row (the document) belongs.
I'm using TF-IDF Vectorizer in sklearn. I want to get rid of anything that's not an english language word, so I'm using the following:
class LemmaTokenizer(object):
    def __init__(self):
        self.wnl = WordNetLemmatizer()
    def __call__(self, doc):
        return [self.wnl.lemmatize(t) for t in word_tokenize(doc)]

s_words = list(nltk.corpus.stopwords.words("english"))

c = TfidfVectorizer(sublinear_tf=False,
                    stop_words=s_words,
                    token_pattern =r"(?ui)\\b\\w*[a-z]+\\w*\\b",
                    tokenizer = LemmaTokenizer(),
                    analyzer = "word",
                    strip_accents = "unicode")

#a_df is the original dataframe
X = a_df['Text']
X_text = c.fit_transform(X)

which as far as I know, when calling c.get_feature_names() should return only the tokens which are proper words, without numbers or punctuation symbols.
I found the regex in a post in StackOverflow, but using a simpler one like [a-zA-Z]+ will do exactly the same (this is, nothing).
When I call the feature names, I get stuff like
["''abalone",
"#",
"?",
"$",
"'",
"'0",
"'01",
"'accidentally",
...]

Those are just examples, but it's representative of the output I get, instead of just the words.
I've been stuck with this for days trying different regular expressions or methods to call. Even hardcoded some of the outputs for the features on the stop words.
I'm asking this because later I'm using LDA to get the topics of each cluster and get punctuation symbols as the "topics".
I hope I'm not duplicating another post. Anymore information I need to provide will do gladly. Thank you in advance!

A: The regex pattern gets ignored if you pass a custom tokenizer. This is not mentioned in the documentation, but you can see it clearly in the source code here:
https://github.com/scikit-learn/scikit-learn/blob/9e5819aa413ce907134ee5704abba43ad8a61827/sklearn/feature_extraction/text.py#L333
def build_tokenizer(self):
    """Return a function that splits a string into a sequence of tokens.
    Returns
    -------
    tokenizer: callable
          A function to split a string into a sequence of tokens.
    """
    if self.tokenizer is not None:
        return self.tokenizer
    token_pattern = re.compile(self.token_pattern)
    return token_pattern.findall

If self.tokenizer is not None, you will not do anything with the token pattern.
Solving this is straightforward, just put the regex token pattern in your custom tokenizer, and use this to select tokens.


text:
Q: Как организовать одновременную работу Telegram бота (Aiogram) и Flask? Всем доброго времени суток!
Нужен совет.
У меня есть бот (написанный с помощью telebot) и API (Flask), которые запущены в двух потоках и спокойно работают одновременно. Бот запущен через polling.
API занимается обработкой входящих POST запросов с нескольких адресов.
Сейчас переписываю бота с использованием aiogram.
Знаю, что нельзя смешивать асинхронность и потоки, но возникает трудности с одновременной работой этих двух модулей. Работает либо бот, либо API.
Какие есть варианты подружить Flask и Aiogram, или же стоит отказаться от использования Flask и обрабатывать запросы другим способом?
Также читал про вариант с webhook`ами, вроде там можно отлавливать POST-запросы, и тогда Flask не нужен.
Пробовал вариант с запуском в разных потоках:
import threading
import time
from time import sleep
from flask import Flask,request
from flask_restful import Api, Resource
import config
import asyncio,hashlib,requests,threading,time
import logs
from aiogram import Bot, Dispatcher, executor, types
from asyncio import new_event_loop, set_event_loop

app = Flask(__name__)
api = Api(app)
dp = Dispatcher(Bot(token=config.bot_token))

@dp.message_handler(commands="start")
async def message_start(message: types.Message):
    await message.answer("HI")

@app.route('/test', methods=['POST'])
def get_test():
    data = request.get_json()
    print (data)
    return ("ok")

def app_run():
    while True:
        try:
            app.run()
        except Exception as ex:
            print(ex)

def bot_polling():
    try:
        executor.start_polling(dp, skip_updates=True)
        set_event_loop(new_event_loop())
    except Exception as ex:
        print(ex)

bot_thread = threading.Thread(target=bot_polling)
bot_thread.daemon = True
bot_thread.start()

app_thread = threading.Thread(target=app_run)
app_thread.daemon = True
app_thread.start()

if __name__ == "__main__":
    while True:
        try:
            sleep(1)
        except KeyboardInterrupt:
            break

Пробовал через асинхронность с помощью встроенной в aiogram on_startup:
import threading
import time
from time import sleep
from flask import Flask, jsonify, request
from flask_restful import Api, Resource
import config
import asyncio,hashlib,requests,threading,time
import logs
from aiogram import Bot, Dispatcher, executor, types
from asyncio import new_event_loop, set_event_loop

app = Flask(__name__)
api = Api(app)
dp = Dispatcher(Bot(token=config.bot_token))

@dp.message_handler(commands="start")
async def message_start(message: types.Message):
    print("hi")
    await message.answer("HI")

@app.route('/test', methods=['POST'])
def get_test():
    data = request.get_json()
    print (data)
    return ("ok")

async def is_enabled():
  while True:
    await app.run()

async def on_startup(x):
    asyncio.create_task(is_enabled())

if __name__ == '__main__':
    executor.start_polling(dispatcher=dp, skip_updates=True, on_startup=on_startup)

A: Вариант с потоками почти правильный. Нужно только loop создать до вызова start_polling:
        set_event_loop(new_event_loop())
        executor.start_polling(dp, skip_updates=True)

С асинхронным тоже можно. Вот так будет работать:
...

async def on_startup(x):
    asyncio.create_task(asyncio.to_thread(app.run))

if __name__ == '__main__':
    executor.start_polling(dispatcher=dp, skip_updates=True, on_startup=on_startup)

Есть только проблема с остановкой flask, есть способы и ее побороть.


text:
Q: Link não funciona ao ser clicado Tenho esse código de um menu e ao ser clicado no item Biografia o link não funciona:

HOME

BIOGRAFIA

DISCOGRAFIA

FOTOS

VIDEOS

AGENDA

CONVITE

CONTATO

Código CSS:
#ul-menu {
   text-align: center;
   padding-top: 25px;
   word-spacing: 50px;
}

.li-menu {
    display: inline;
    font-family: 'Abel', sans-serif;
 }

.li-menu a {
    color: white;
    text-decoration: none;
    font-size: 15px;
    background: #483D45;
    -moz-transition: all 0.2s linear;
    -webkit-transition: all 0.2s linear;
    -o-transition: all 0.2s linear;
    transition: all 0.2s linear;
}

Já coloquei o destino do link no "href" mas quando eu clico não vai.

A: No  da página, tem um script:
jQuery(document).ready(function($) {
    $(".scroll").click(function(event){
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 200);
    });
});

O seu link tem a classe scroll, por isso está disparando o evento configurado em $(".scroll").click. O método event.preventDefault() interrompe a navegação do link. Para corrigir, remova o preventDefault ou remova a classe scroll do link.
Além disso, o script está dando o seguinte erro:

Uncaught TypeError: Cannot read property 'top' of null


text:
Q: Readonly target in Vue composition API My "Generateur" component is sending props to my "Visionneuse" component. Everything works fine inthe browser, but I have this message in the console:
Set operation on key "texteEnvoye" failed: target is readonly.

I really have no clue why I get this message, because I pass the prop to a ref.
Here are my components:
"Generateur"
<template>

Génération d'une carte de voeux

      <Visionneuse :texteEnvoye="texte" :taille="0.5"/>

    <textarea
      :style="'width: 60%; resize:none;height: 100px;'"
      v-model="texte"
      placeholder="Écrivez votre texte ici">
    </textarea>

    <button
      v-if="lien.length == 0"
      id="boutonObtenirLien"
      v-bind:class="{ enCours: lienEnCours }"
      class="btn first"
      @click="obtenirLien">Obtenir le lien</button>

 0">
      Votre carte de voeux est accessible au lien suivant:

      {{ lien }}

</template>

And the "Visionneuse"
<template>

    <canvas
      ref='carte'
      :width="size.w"
      :height="size.h"
      tabindex='0'
      style="border:1px solid #000000;"
    ></canvas>

      {{ p }}

</template>

A: OK I found a solution. I separate "texteEnvoye" and "texte" and everything works fine. I don't know if this is a good way to code in composition API but it did the trick:
<template>

    <canvas
      ref='carte'
      :width="size.w"
      :height="size.h"
      tabindex='0'
      style="border:1px solid #000000;"
    ></canvas>

      {{ p }}

</template>

A: I know you answered your own question.  For the 'why', you aren't supposed to change props in the composition API, because props are used to pass reactive data from parent components to child components.  The pattern is: events from child to parent, mutation from parent to child .  toRef makes the data reactive, but it doesn't affect whether you can mutate it.  So if you go:
const texteEnvoye = toRef(props, 'texteEnvoye');
texteEnvoye.value='foo'; // not allowed - texteEnvoye.value is read-only

if you go:
const texteEnvoye = ref('');
const texteEnvoyeRo = toRef(props,'texteEnvoye'); // react to prop
watch(texteEnvoyeRo, (value) => {
  textEnvoye.value = texteEnvoyeRo.value; // OK, textEnvoye is yours
});

now texteEnvoye is yours, and you can mutate it, and react to changes in textEnvoyeRo.


text:
Q: Does $\lfloor \tan (n)\rfloor =n$ have infinite roots? Background
This post can be understood as the gap between $\tan n$ and $n$ has no upper limit.
Does the sequence $n+\tan(n), n \in\mathbb{N}$ have a lower bound?
I want to know how close $\tan n$ can be to $n$.
I try to find some solution with difference less than 1.
$$|\tan n -n|<1$$
or similar
$$\lfloor \tan (n)\rfloor =n$$
$\lfloor x\rfloor$ means floor function.
I did a quick search for $n<10^7$ and found no solution other than $n = 0,1$
Question
Is there an infinite number of integers n that make the equation true, and how big will the next solution be?

A: Not an answer, but a heuristic, assuming $n\bmod 2\pi$ is a random number from $[0,2\pi).$
If $n>0$ is a solution, then we have a solution if:
$$\arctan(n-1)<n-\pi\left\lfloor \frac n{\pi}\right\rfloor<\arctan(n+1)$$
When $n\bmod \pi\leq\arctan(n),$ $-n$ is the solution.
So if $n\bmod {\pi}$ is treated as a random variable, the probability that you have a solution in $\pm n$ is $$\frac{\arctan(n+1)-\arctan(n-1)}{\pi}.$$
This means the expected number of solutions $\pm n$ for $n>1$ would be: $$\sum_{n=2}^{N}\frac{\arctan(n+1)-\arctan(n-1)}{\pi}=\frac{\arctan(N+1)+\arctan(N)-(\arctan 1+\arctan 2)}{\pi}\to\frac{\pi-\arctan 1-\arctan 2}{\pi}\approx 0.4.$$
So heuristically, it is not surprising that there might be zero solutions.
This can be made probabilistic. If $X$ is a uniform random variable in $[0,2\pi)$ then the expected number of integers $n\neq 0,1,-1$ such that $n>0$ such that $\lfloor\tan(X+n)\rfloor=n$ is $$\frac{\pi-\arctan(1)-\arctan(2)}{\pi}$$
Allowing $n=\pm1$ you'd get an expected count of $\frac3{4}.$ Adding $n=0$ we get an expected count of exactly $1.$

That $1$ is not actually surprising - it follows from a general rule.
Given an interval $[a,b]$ and disjoint measurable subsets $\{A_n\}_{n\in \mathbb Z}$ of $[a,b],$ uniform random variables $\{X_n\}_{n\in\mathbb Z},$ not necessarily independent, then the expected number of $X_n\in A_n$ is $$\mu(\bigcup_{n\in\mathbb Z} A_n),$$ where $\mu$ is the probability measure on $[a,b].$
In the initial problem, we can take $[-\pi/2,\pi/2)$ and $X_0$ to be a uniform random variable, and $X_n=(X_0+n)\bmod{\pi}.$ We take $A_n=[\arctan(n),\arctan(n+1)].$ Then $\bigcup A_n=(-\pi/2,\pi/2)$ so the expected number of $X_n\in A_n$ is $1.$

Technically, the general resul for this is false. But if $C_N$ is the number of $|n|\leq N$ such that $X_n\in A_n,$ then $$E(C_N)=\sum_{n=-N}^{N}\mu(A_n).$$
But in the specific case where $X_n=X_0+n\bmod2\pi,$ the measure of the values $x_0$ which given infinitely many $X_n\in A_n$ has zero measure, so then we can define $E(C_{\infty}).$
But the set of $x_0$ with at least one $x_0+n\bmod\pi$ with $|n|>N$ has measure at most $p_N=\mu(B_{N}),$ where $B_N=\bigcup_{|n|>N}A_n.$ But $\mu(B_N)\to0.$
So $\bigcap_{N=1}^{\infty} B_N$ has measure $0$ and is the set of problematic $x_0.$

A: According to https://oeis.org/A249836 (6th comment), $n = 0, 1$ are the only currently known solutions. You can also refer to https://oeis.org/A258024.

A:
I want to know how close $\tan n$ can be to $n$.

Well, it's exactly equal if $n = 0$, but that's a boring answer.
Otherwise, here are the smallest values of $|\tan n - n|$ that I've found for $|n| \le 10^7$, using simple brute force:

*

*$n = \pm 1$, error ≈ 0.557408.  As noted, $n = +1$ is the only known nonzero solution to $\lfloor \tan n \rfloor = n$.

*$n = \pm 4$, error ≈ 2.842179

*$n = \pm 3$, error ≈ 3.142547

*$n = \pm 2$, error ≈ 4.185040

*$n = \pm 7$, error ≈ 6.128552

*$n = \pm 6$, error ≈ 6.291006

*$n = \pm 14$, error ≈ 6.755393

*$n = \pm 5$, error ≈ 8.380515

*$n = \pm 10$, error ≈ 9.351639


text:
Q: rubymine debug rspec Uncaught exception: cannot load such file -- teamcity/spec/runner/formatter/teamcity/formatter i setup a rails project and i cant get rspec to run in rubymine. Here are my testing gems:
group :development, :test do
  gem 'rspec-rails'
  gem 'shoulda-matchers'
  gem 'factory_girl_rails', require: false
end

group :test do
  gem 'faker'
end

and here is my error message
/Users/dude/.rvm/rubies/ruby-2.1.2/bin/ruby -e at_exit{sleep(1)};$stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Users/dude/.rvm/gems/ruby-2.1.2@myproject/gems/ruby-debug-ide-0.4.23.beta1/bin/rdebug-ide --disable-int-handler --port 53125 --dispatcher-port 53126 -- /Users/dude/.rvm/gems/ruby-2.1.2@myproject/bin/rspec /Users/dude/Code/myproject/spec/models/instagram_user_spec.rb --require teamcity/spec/runner/formatter/teamcity/formatter --format Spec::Runner::Formatter::TeamcityFormatter --example InstagramUser --require /Applications/RubyMine.app/rb/testing/patch/bdd/teamcity/spec/runner/formatter/teamcity/rspec3_formatter.rb
Testing started at 9:03 PM ...
Fast Debugger (ruby-debug-ide 0.4.23.beta1, debase 0.0.9) listens on 127.0.0.1:53125
Uncaught exception: cannot load such file -- teamcity/spec/runner/formatter/teamcity/formatter
    /Users/dude/.rvm/gems/ruby-2.1.2@myproject/gems/rspec-core-3.0.4/lib/rspec/core/configuration.rb:1025:in `require'
    .......
Process finished with exit code 0

A: i reinstalled rubymine and now the builtin rspec debugger works fine.


text:
Q: Overriding initialize error test environment I am having a hard time understanding an error with ruby's open classes. Overriding a method in test environment (rails) causes an invalid arguments error on initialize. For some reason, overriding the new method solved the problem. Why?
My class:
require 'adwords_api'
require 'adwords_config'
require 'scanf'

class AdwordsHelper
  attr_accessor :adwords_id
  attr_accessor :campaign_id
  attr_accessor :adgroup_id
  attr_accessor :invalid_ops

  @@RETRY_INTERVAL = 3
  @@RETRIES_COUNT = 500
  @@config = 'adwords_api.yml'

  def initialize(args = {})
    self.adwords_id = AdwordsConfig.config[:master_account]

    return unless args.is_a?(Hash)
    args.each do |k,v|
      instance_variable_set("@#{k}", v) unless v.nil?
    end
  end

  def set_budget(budget)
    @api = get_adwords_api
    budget_id = get_budget_id

    service = @api.service(:BudgetService)
    operation = {
      :operator => 'SET',
      :operand => {
        :budget_id => budget_id,
        :amount => {
          :micro_amount => budget
        }
      }
    }

    service.mutate([operation])
  end
end

Now in the test, I want to override one of the methods, because I don't want there to be communication with the actual adwords servers.
require "test_helper"
# FIXME override this in another file eventually
class AdwordsHelper
  def set_budget(budget)
    true
  end
end

Calling
AdwordsHelper.new(campaign_id: 1)

gives an invalid arguments 1 for 0 error.
Now, overriding the new function, solves the error.
class AdwordsHelper
  def self.new(*args, &block)
    obj = allocate
    obj
  end
  def set_budget(budget)
    true
  end
end

Is overriding the method set_budget causing other quirks?

A: Try
AdwordHelper.class_eval do
  def set_budget(budget)
    true
  end
end

class AdwordHelper will define the class when the original AdwordHelper is not loaded already, in which case the only method that exists in your class is set_budget. It wouldn't know about the initialize with one argument.
Whereas, if you use class_eval, it tries to load the file containing AdwordHelper class and then add the method set_budget to the class.


text:
Q: Decoding a Unicode string; what does that mean and how can I avoid it? I'm looking for a simple way of converting a user-supplied string to UTF-8. It doesn't have to be very smart; it should handle all ASCII byte strings and all Unicode strings (2.x unicode, 3.x str).
Since unicode is gone in 3.x and str changed meaning, I thought it might be a good idea to check for the presence of a decode method and call that without arguments to let Python figure out what to do based on the locale, instead of doing isinstance checks. Turns out that's a not a good idea at all:
>>> u"één"
u'\xe9\xe9n'
>>> u"één".decode()
Traceback (most recent call last):
  File "<ipython-input-36-85c1b388bd1b>", line 1, in <module>
    u"één".decode()
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

My question is two-fold:

*

*Why is there a unicode.decode method at all? I thought Unicode strings were considered "not encoded". This looks like a sure way of getting doubly encoded strings.

*How do I tackle this problem in a way that is forward-compatible with Python 3?

A: It's not useful to speak of "decoding" a unicode string. You want to encode it to bytes. unicode.decode is solely there for historical reasons; its semantics are meaningless. Therefore, it has been removed in Python 3.
However, the encode/decode semantics have historically been extended to include (character) string-to-string or byte-to-bytes encodings such as rot13 or bzip2. In Python 3.1, these pseudo encodings were removed, and reintroduced in Python 3.2.
In general, you should design your interfaces so that they either accept character or byte strings. An interface that accepts both (for reasons other than backwards compatibility) is a code smell, hard to test, prone to bugs (what if someone passes UTF-16 bytes?) and has questionable semantics in the first place.
If you must have an interface that accepts both character and byte strings, you can check for the presence of the decode method in Python 3. If you want your code to work in 2.x as well, you'll have to use isinstance.

A: Conversion between str and unicode is not the only purpose of encode/decode.  There are also codecs.
For example (in Python 2):
>>> u'123'.encode('hex')
'313233'
>>> '313233'.decode('hex')
'123'
>>> u'313233'.decode('hex')
'123'

I'm not sufficiently familiar with Python 3 to be able to say whether or not this works there.

A: *

*The Unicode object has a decode() method because it inherits from basestring and basestring has one, so Unicdode has to have one as well.

*You tackle the problem by never decoding Unicode strings, in Python 2 or Python 3. As you note, it makes no sense to do so. So don't.
How then do you handle this in a compatible wait in Python 2 and Python 3? well, you don't use strings for binary data, you use bytes. They have a decode() method that works in all versions of Python.
For more information on this see http://python3porting.com/noconv.html and also http://regebro.wordpress.com/2011/03/23/unconfusing-unicode-what-is-unicode/


text:
Q: at what probability will the probability we start considering the data? For example I have this problem,
Do Americans tend to vote for the taller of the two candidates in a presidential election? In 30 presidential elections since 1856, 18 of the winners were taller than their opponents. Assume that Americans are not biased by a candidate's height and that the winner is just as likely to be taller or shorter than his opponent. Find the approximate probability of finding 18 or more of the 30 pairs in which the taller candidate wins.
Based on your answer, can you conclude that Americans consider a candidate's height when casting their ballot.
To solve this problem I have used normal approximation for binomial distribution. With p=0.5 (because we are assuming that they are unbiased), and found 0.1814
However, I am not sure how to answer the second part of the question, I would like to know at what probability will they consider a candidate's height.


text:
Q: Openssl ECDSA sign input as-is - without digest I am trying to sign an existing digest with openssl.
Let's say I already have a digest 'mydigest'. With that said I dont want to use:
echo -n "mydigest" | openssl dgst -sha256 -sign key.pem | openssl enc -A -base64

I have ECDSA not rsa so I assume I should not use rsautl which is using the input as-is.
So my assumption is that I would need something which takes input as-is (mydigest) and sign it with my ECDSA private key.
I tried following in order to see if the size of hash created with different hash algorithm has any affect on sign result:
echo -n "mydigest" | openssl pkeyutl -sign -inkey key.pem | openssl enc -A -base64

and
echo -n "my-very-very-very-long-digest" | openssl pkeyutl -sign -inkey key.pem | openssl enc -A -base64

but the size of the outputs is same for both commands in terms of output length. I would assume for the large my-very..-long-digest it should return larger output (because it should take the input as-is without shortening (hashing).
========================================
EDIT.
Maybe the example below will help to understand what I am asking. This is an example with bouncycastle.
 // sign something
String messageToSign = "something_to_sign";
ECDomainParameters domain = new ECDomainParameters(spec.getCurve(), spec.getG(), spec.getN());
ECDSASigner signer = new ECDSASigner();
signer.init(true, new ECPrivateKeyParameters(privateKey, domain));
MessageDigest digest = MessageDigest.getInstance("Keccak-256");
byte[] hash = digest.digest(messageToSign.getBytes(StandardCharsets.UTF_8));
BigInteger[] signature = signer.generateSignature(hash);

Let's assume I have following:

*

*hash.

*keys.

And now I want to create signature with openssl which should take the hash and keys as an input without creating the hash. Basically I want to replace
BigInteger[] signature = signer.generateSignature(hash);

in the example with openssl.
openssl * ????? *

I assumed the size of the results should indicate if the hash (with different digest size) algorithm I use for hash has any affect on results.

A: openssl pkeyutl -sign -inkey ecprivkey.pem is entirely correct.

I would assume for the large my-very..-long-digest it should return larger output (because it should take the input as-is without shortening (hashing).

You assumed wrongly. An ECDSA signature mathematically consists of two integers (r,s) in the range 1 to the order of the curve subgroup; it is completely unaffected by the size of the hash used as (or on) the input.  It is recommended to use a hash whose size matches the subgroup -- e.g. SHA256 (or your Keccak256) with P-256 aka secp256r1 -- because otherwise if the hash is too large it is truncated or if too small it is padded and either reduces security.
The same is true for DSA, and mostly for RSA -- for RSA the signature is always the size of the RSA key, and an encoded-and-padded hash smaller than the RSA key is padded, but a too-large one is rejected as an error. (This is very rare, because RSA keys below 2048 bits are no longer considered acceptably secure for use, and no one uses hashes that big.)
The size of an ECDSA signature representation -- or encoding -- can vary and there are several different standards. OpenSSL always uses the ASN.1 SEQUENCE of INTEGERs shown in rfc3279 2.2.3. So do the standard SunEC and BouncyCastle providers in Java by default. The length of the ASN.1 encoding depends, usually only slightly, on the values of the two integers which as you correctly note are controlled by a random value (k) and thus effectively pseudo-random numbers themselves. See (ADDED) Java ECDSAwithSHA256 signature with inconsistent length and (cross) https://crypto.stackexchange.com/questions/33095/shouldnt-a-signature-using-ecdsa-be-exactly-96-bytes-not-102-or-103 and https://crypto.stackexchange.com/questions/44988/length-of-ecdsa-signature
The Bouncy provider also supports '{hash}with{PLAIN-,CVC-}ECDSA' algorithms which do the same mathematical signature but use the simpler representation defined by P1363, simply two (unsigned bigendian) integers of fixed size (equal to the subgroup order size) concatenated. EDIT: And the SunEC provider since Java 9 does so with the different name '{hash}withECDSAinP1363format' (somehow I missed this on first writing). JWS also uses this representation. Finally, the Bouncy LWAPI which you showed returns or takes BigInteger[] -- the mathematical value -- and leaves the encoding and decoding up to you.


text:
Q: How do I disable my laptops builtin keyboard? I have a problem with my laptops default keyboard. It is broken... to sum up.
It gets stuck on the 'h' key and you see
ghsdhhhhhhhhhhhhhhhhhhhhhhhhhhhhh... ----> (arrow signifies that it goes on forever until I stop it)
I use a USB keyboard to type. I want to disable the default keyboard because I don't want to deal with this anymore. Is there a way to do that with ubuntu?

A: Please refer to:
How to get Xorg to ignore certain input devices?

Input devices are now managed in /usr/share/X11/xorg.conf.d/ (in 10.04 Lucid, the directory is /usr/lib/X11/xorg.conf.d/).
  This directory contains configuration rules for all your input devices:
root@3000-G530:/usr/share/X11/xorg.conf.d# ls
  10-evdev.conf      50-vmmouse.conf  51-synaptics-quirks.conf
  50-synaptics.conf  50-wacom.conf    60-magictrackpad.conf
You fist need to find your input device there, note that those files are "rules" matching a number of possible devices. 50-wacom.conf for example will handle every wacom device. Look throgh them to find which one is responsible for your device, or create your own.
  To disable a device:
Add the option Option "Ignore" "true" to the relevant configuration file.
Open the file with root privileges (i.e. press Alt+F2 and type gksu gedit) and add this option to the others.
Log out and back in for the changes to take effect.


text:
Q: Next.js fetch a token from an api on initial render and store it I'm building an application using next.js, there is a need to fetch a guest token from an api and set in the cookie as it would be needed throughout the application. So the first thing I want is the token to be set in the cookie before any page is loaded.
I'm migrating from react, there this logic was there in the app.js file and it was a single page application.
I tried putting the logic in getServerSideProps in the home page, it worked fine and the cookie was set, but the issue was if the user go to any other page first directly, the cookie won't  be there. To achieve that we have to duplicate this code in that page as well. (which I don't want as there are lot of pages)
Then on further research, I came to know that we can use getInitialProps in the _app file, that fetches the initial data for all the pages but it comes with a warning (This disables the ability to perform automatic static optimization, causing every page in your app to be server-side rendered.) Not sure if it would be ideal for this case.
Is there any other solution, like some kind of wrapper we can use on top of _app to fetch the token server side and store it.
I'm new to next.js, please help me with this.

A: If you want to share the same server side logic to all the pages you could use next middleware or next custom server.
Consider that middleware use a subset of the nodejs runtime features so to perform http request you have to use the custom server. AIf you want you can then left to the middleware just the set/check of the cookies.


text:
Q: Very simple : textarea with min height-rows and 100% height? I have a div containing a textarea element.
And I need to give it the right vertical size.
The container Div have right size. (100%)
I want to give a min-height or min rows, to provide a scroll if necessary, and a height of 100% (the 100 % of div).
I can't. I don't know how to do this. I need an example.

A: The very basic example is
<html>
<body>

<div style="height:100%;border:1px solid green;">
    <textarea style="min-height:100px;height:100%;width:100%;border:1px solid red;"></textarea>
</div>

</body>

Borders are only to show dimensions. But in your case it might be more complicated. Please look at the definition of a containing block and height calculation.


text:
Q: 2-Column CSS List breaking when one side is bold This is something that I figure should be straightforward, but I can't seem to figure it out, and spending a couple of hours on a single list is driving me nuts.
What I'm trying to do is create a 2-column list, with "labels" on one side, and values on the other. I can get it to work if I leave font weights normal, or have both sides bold, but as soon as I make the labels bold and values normal, it staircases.
A screenshot of it with bold
A screenshot without bold
The applicable CSS:
ul.info {
    margin: 0;
    padding: 0;
    list-style: none;
}

ul.info li.name {
    width: 150px;
    float: left;
    font-weight: bold;
}

ul.info li.value {
}

The HTML:

Member Since

<?=$user->registerTime ?>

Last Logged in

<?=($user_login !== null ? $user_login->login_time : 'Never') ?>

Email verified?

<?=($user->emailVerified ? 'Yes' : 'No') ?>

I've narrowed it down to the bold, but it doesn't make sense why that would break it. Any ideas?

A: I suspect it will be down to the bold elements having extra vertical space being added somehow, which would explain why the floating isn't becoming staggered. Do you have a consistent line-height property applied to the list elements?
You'd be much better off using a definition list, rather than an unordered list. That way you can style dt and dd elements entirely separately, with the added advantage of your markup being much more semantic.

A: You could try setting the height or min height of you LIs to a pixel figure greater than the height of the bolded font.

A: What browser? It works fine for me in chrome.
I would suggest checking the script codes.. if they are generating valid xhtml.
proof


text:
Q: Laravel Call to a member function delete() on null in PegawaiController i use join to take nama_departemen from Departemen table
public function index()
{
    $data_pegawai = Pegawai::join('departemens','pegawais.id_departemen','=','departemens.id')->paginate(5);
    return view ('pegawai.index', compact('data_pegawai'));
}

public function destroy($id)
{
    Pegawai::find($id)->delete();

    return redirect()->route('pegawai.index')->with(['success'=> 'Item Berhasil Dihapus']);
}

in pegawai.index
@forelse ($data_pegawai as $item)

                                            {{ $item->nomor_induk_pegawai }}
                                            {{ $item->nama_pegawai }}
                                            {{ $item->nama_departemen }}
                                            {{ $item->email }}
                                            {{ $item->telepon }}
                                            @if($item->gender==0)
                                            Wanita
                                            @else
                                            Pria
                                            @endif

                                            @if($item->status==0)
                                            Inactive
                                            @else
                                            Active
                                            @endif

                                                <form onsubmit="return confirm('Apakah Anda Yakin ?');" action="{{ route('pegawai.destroy', $item->id) }}" method="POST">
                                                    id) }}" class="btn btn-sm btn-primary">EDIT
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="submit" class="btn btn-sm btn-danger">Hapus</button>
                                                </form>

                                    @empty

                                        Data Pegawai belum tersedia

                                    @endforelse

im trying to delete data with DELETE button. it said Call to a member function delete() on null but sometimes it work. i use the same code for delete button in departemen.index and it working fine. how to fix this?

A: Sometimes it's working because the data is not deleted in that case it works. And when data is deleted and you are redirecting again that page then an error will throw as  Call to a member function delete() on null.
To ignore this value you have to simply create a list view. when you are redirecting to the list view which contains all data which are not deleted

A: First, you need check if there is a record with that ID before trying delete it.
The best way to do it is typing the param.
In Controller:
public function destroy(Pegawai $pegawai)
{
    $pegawai->delete();

    return redirect()->route('pegawai.index')->with(['success'=> 'Item Berhasil Dihapus']);
}

In the route file you need change the param name from $id to $pegawai.
Laravel will check if the ID is valid before enter into the function.


text:
Q: How to allow chords of keyboard keys to change the keymap temporarily? I have really gotten used to the "Simultaneous Vi Mode" functionality of KeyRemap4MacBook which lets you press and hold the s and d keys simultaneously and then use the h, j, k, and l keys as the arrow keys.  When s and d are pressed together, no s or d event is fired, but when I type normally I don't notice any delay problems with hitting s or d individually.
How could I recreate this functionality in Linux (specifically RHEL 6.4)?
A couple ideas I had:

*

*If s+d could be remapped to a modifier, then the keys h,j,k,l+modifier could be mapped accordingly.  (The keyboard I am using now does not have any spare modifier keys available to use instead of s+d, plus the point of Simultaneous Vi Mode is to keep all fingers on the home row.  CapsLock is already remapped to Control and Escape).

*Ideally, I would find a way to do this using system settings or something like XKB keyboard which I am using already.  If that's not possible, perhaps something similar to the xcape program (which I am using and which lets keys be mapped to different keypress and modifier key symbols) could be written.  xcape triggers off of key release though, so it would have to be tweaked to keep the s and d keys from being too slow.

A: So after four years, I finally have a rough draft of an answer to this question. The answer is to use Interception Tools which uses libevdev to grab keyboard input and do processing on it before re-emitting it. Regarding simultaneous key mapping, I have made a rough plugin for Interception Tools called Chorded Keymap that lets h, j, k, l act like the arrow keys when s and d are pressed simultaneously.

A: You can't do this with the standard tools, you would have to write something (probably a lot of the xserver will be affected, and if you want this to work outside X, there will be kernel changes).
The reason for this is that the ideas the design is based on (and optimized for) does not include chording of regular keys or emitting characters from modifiers.

A: You would need to get a programmable adapter that sits between your keyboard and computer. They're out there but hard to find.
Or go a tad further, for example: https://www.youtube.com/watch?v=ixbVd8rn6-8


text:
Q: How to fetch data in weather API on Redux with parameters? My question is simple as how can i get city and country , on axios fetch  with multiple parameters on URL with Redux?
in the ROOT_URL the parameters are city and country change
const URL = `http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`;

my actions
import axios from 'axios';
const API_KEY = "a3de5cffde10c377d199699b3da6fc6f";

export function getWeather (city, country) {
    const URL = `http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`;

    return(dispatch)=>{
        return axios.get(URL)
        .then(res => {
            dispatch(changeWeather(res));
        }).catch(err =>{
            console.log('error', err);
        });

    }
}
const changeWeather = weather => ({
    type: 'CHANGE_WEATHER',
    weather
});

the reducers
const weatherDefaultState = {
    city:undefined,
    country:undefined,

};
export default (state=weatherDefaultState,action)=>{
    switch(action.type) {
        case 'CHANGE_WEATHER':
        return {...state, weather: action.weather}
        default: return state;
    }
};

and the component with redux, runs but the button does not perform any action, what is the error ?
   import React from 'react';
import {connect} from 'react-redux';
import { getWeather } from '../actions/weather';
class Weather extends React.Component {

    loadWeather = () => {
        const API_KEY = 'a3de5cffde10c377d199699b3da6fc6f';
        const URL = `http://api.openweathermap.org/data/2.5/weather?q=Merida,mx&appid=${API_KEY}&units=metric`;

        return(dispatch)=>{
            return axios.get(URL)
            .then(res => {
                dispatch(getWeather(res));
            }).catch(err =>{
                console.log('error', err);
            });

        }
    }
    render() {
        return(

            <WeatherForm
                 weather={this.props.weather}
                 handleClick={this.loadWeather}
            />

        )
    }
}

class WeatherForm extends React.Component {
    render() {
        return(

            <button
            className='boton-color'
            style={{backgroundColor:'darkcyan'}}
            onClick={()=>{this.props.handleClick() }}
            type="button" >

            clima
</button>

)
    }
}
const mapStateToProps = (state) => {
    return state
};
export default connect(mapStateToProps)(Weather);

A: According to your code, you don't make HTTP call at all.
Inside your loadWeather function, which is just method on the component, you return a function which takes dispatch as an argument, this isn't correct.
You have your async action, which is great ( I assume you have installed and connected redux-thunk properly.
So, you need to get access to this action inside your component. This should be made using connect module which you installed and connected. But it also takes another parameter to connect actions to props.
const mapStateToProps = (state) => {
    return state
};

/* This one you should add */
const mapDispatchToProps = dispatch => {
   return {
      getWeatherDispatch: (city, country) => {
          dispatch(getWeather(city, country))
      }
   }
};
export default connect(mapStateToProps, mapDispatchToProps)(Weather);

As a result, you can invoke your action inside a component using this.props.getWeatherDispatch(yourCity, yourCountry)


text:
Q: how to get current minutes php i need a simple script to print the current minutes.
but ONLY the minutes(or seconds ^^).
in php

A: use date('i') to show minutes or date('s') for seconds.
http://php.net/manual/en/function.date.php


text:
Q: How can I show the window in WPF without lost controls? I have a program when I log in, I have to wait for loading database from server. So I created a "Loading..." window. After loading the database, this will automatically close the "Loading" window, the "Login" window and open the MainWindow.xaml.
But myprogram have a problem: when I use waitForm.show() in Login.xaml.cs, it runs good, but the controls on "Waiting" window like progressbar, textblock, it doesn't display.If I use waitForm.showdialog(), it will display progressbar and textblock control. But it won't automatically close. So my Mainwindow.xaml not open.
Is it possible to use show() but show the controls?
Sorry about my bad English. Thank you.
Waiting.xaml
<Window x:Class="TMO.Waiting"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TMO"
        mc:Ignorable="d"
        Title="Waiting" Height="100" Width="300" WindowStartupLocation="CenterScreen" WindowStyle="None">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <ProgressBar Margin="10,20,10,5" Minimum="0" Maximum="100" Name="pbStatus" IsIndeterminate="True" Grid.Row="0"/>
    <TextBlock Grid.Row="1" Margin="0,5,0,5" TextAlignment="Center" VerticalAlignment="Center" FontSize="20" FontWeight="Bold" >Loading...</TextBlock>
    </Grid>
</Window>

Waiting.xaml.cs
using System.Windows;

namespace TMO
{
    /// <summary>
    /// Interaction logic for Waiting.xaml
    /// </summary>
    public partial class Waiting : Window
    {
        public static MessageBoxResult result;
        public Waiting()
        {
            InitializeComponent();
        }
        public Waiting(Window parent1)
        {
            InitializeComponent();

        }
        public void CloseWaiting()
        {
            DialogResult = true;
            this.Close();
        }
    }
}

WaitFunc.cs
using System.Threading;
using System.Windows;
namespace TMO
{
    public class WaitFunc
    {
        Waiting wait;
        Thread loadthread;
        public void show()
        {
            loadthread = new Thread(new ThreadStart(LoadingProcess));
            loadthread.Start();
        }
        public void show(Window parent)
        {
            loadthread=new Thread(new ParameterizedThreadStart(LoadingProcess));
            loadthread.Start(parent);
        }
        public void Close()
        {
            if(wait!=null)
            {
                wait.Dispatcher.BeginInvoke(new System.Threading.ThreadStart(wait.CloseWaiting));
                wait=null;
                loadthread=null;
            }
        }
        public void LoadingProcess()
        {
            wait=new Waiting();
            wait.ShowDialog();
        }
        public void LoadingProcess(object parent)
        {
            Window parent1 = parent as Window;
            wait=new Waiting(parent1);
            wait.ShowDialog();
        }
    }
}

Login.xaml.cs
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
    this.Hide();
    Waiting waitForm = new Waiting();
    waitForm.Show();      //If I use waitForm.showdialog() it will display all control
    Thread.Sleep(500);
    MainWindow main = new MainWindow(txtUserName.Text);
    this.Hide();
    waitForm.Close();
    main.Show();
    this.Close();
}

A: You should manage all windows of the application launch sequence from the entry point of your application. Therefore, I recommend to move the logic to start the MainWindow from the Login.xaml.cs to the App.xaml.cs.
Furthermore, to create a UI thread that can show controls and allows input handling you must explicitly configure the thread to be a STA thread and additionally start the Dispatcher message loop.
Note, if you use async APIs and background threads when necessary (use Task.Run and not Thread), then you don't need an extra UI thread only to show the splash screen.
You should add a LoginSuccessful and a LoginFailed event to the LoginWindow.
Your flow could be implemented like this:
App.xaml
<Application Startup="App_OnStartup" />

App.xaml.cs
public partial class App : Application
{
  private Window SplashScreen { get; set; }

  private void App_OnStartup(object sender, StartupEventArgs e)
  {
    ShutdownMode = ShutdownMode.OnExplicitShutdown;

    var loginScreen = new LoginWindow();
    loginScreen.LoginSuccessful += RunApplication_OnLoginSuccessful;
    loginScreen.LoginFailed += ShutdownApplication_OnLoginFailed;
    loginScreen.Show();
  }

  private void RunApplication_OnLoginSuccessful(object sender, EventArgs e)
  {
    var newUiThread = new Thread(new ThreadStart(ShowSplashScreen))
    {
      ApartmentState = ApartmentState.STA,
      IsBackground = false,
    };

    newUiThread.Start();

    var mainWindow = new MainWindow();
    mainWindow.Loaded += CloseSplashScreen_OnMainWindowLoaded;
    mainWindow.Closed += ShutdownApplication_OnMainWindowClosed;

    // TODO::Initialize application

    mainWindow.Show();
  }

  private void ShowSplashScreen()
  {
    this.SplashScreen = new Window() { Content = "SplashScreen" };
    this.SplashScreen.Show();

    // Start event queue
    Dispatcher.Run();
  }

  private void CloseSplashScreen_OnMainWindowLoaded(object sender, RoutedEventArgs e)
  {
    this.SplashScreen.Dispatcher.InvokeAsync(() =>
    {
      this.SplashScreen.Close();
      this.SplashScreen.Dispatcher.InvokeShutdown();
    });
  }

  private void ShutdownApplication_OnMainWindowClosed(object sender, EventArgs e) => Shutdown();

  private void ShutdownApplication_OnLoginFailed(object sender, EventArgs e) => Shutdown();


text:
Q: Check whether a property of an object exists and only update another property I have an array with objects that look like this:
    let arr = [
        { taxonomy: 'category', id: [ 10, 100 ] },
        { taxonomy: 'post_tag', id: [ 20 ] },
    ];

I want to be able to push a new object in the array that look like this:
    const object = {
        taxonomy: 'category',
        id: 30
    }

What i want is a check if an object in the array with the property value 'taxonomy' already exists, if it does i want to only add the id from the new object in to the existing object. I know how to check if the property already exists but i don't exactly know how to add the new id to the array.
So adding the above object would result in this array:
    [
        { taxonomy: 'category', id: [ 10, 100, 30 ] }, // 30 is added
        { taxonomy: 'post_tag', id: [ 20 ] },
    ];

if it doesn't exist yet it should be added.
Can anybody help me with this?

A: Use Array.find() to locate an object with the same taxonomy in the array. If one exists, add the id to it. If not, push a clone of the object into the array (after converting the object's id to array):

const addUpdate = obj => {
  const current = arr.find(o => obj.taxonomy === o.taxonomy);

  if(current) current.id.push(obj.id);
  else arr.push({
    ...obj,
    id: [obj.id]
  })
};

const arr = [
  { taxonomy: 'category', id: [ 10, 100 ] },
  { taxonomy: 'post_tag', id: [ 20 ] },
];

addUpdate({ taxonomy: 'category', id: 30 });

addUpdate({ taxonomy: 'other', id: 50 });

console.log(arr);

A: You could find the array and update or push a new object with id as array to the array.

const
    array = [{ taxonomy: 'category', id: [ 10, 100 ] }, { taxonomy: 'post_tag', id: [ 20 ] }];
    object = { taxonomy: 'category', id: 30 },
    item = array.find(({ taxonomy }) => object.taxonomy === taxonomy);

if (item) {
    item.id.push(object.id);
} else {
    array.push(Object.assign({}, object, { id: [object.id] }));
}

console.log(array);

   // remove the last insert
   // find item with taxonomy and id
   item =  array.find(({ taxonomy, id }) => object.taxonomy === taxonomy && id.includes(object.id));

// remove from id by using the index
if (item) item.id.splice(item.id.indexOf(object.id), 1);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can use the function forEach for looping and pushing the new id.

let arr = [{taxonomy: 'category',id: [10, 100]},{taxonomy: 'post_tag',id: [20]},],
    object = {taxonomy: 'category',id: 30};

arr.forEach(({taxonomy, id}) => {
  if (object.taxonomy === taxonomy) {
    id.push(object.id);
  }
});

console.log(arr);

A: Using an upsert() function like below, you can accomplish this with a little bit of abstraction, so that it can be re-used for more than just this particular schema. upsert() contains some reasonable defaults for the functions, which would work fine if all the objects are dictionaries with primitive values

function upsert (
  array, object, keyFn,
  updateFn = (target, object) => Object.assign(target, object),
  insertFn = object => object
) {
  const key = keyFn(object)
  const index = array.findIndex(
    value => keyFn(value) === key
  )

  if (index !== -1) updateFn(array[index], object)
  else array.push(insertFn(object))
}

let arr = [
  { taxonomy: 'category', id: [10, 100] },
  { taxonomy: 'post_tag', id: [20] }
]

const obj = { taxonomy: 'category', id: 30 }

upsert(
  arr, obj,
  o => o.taxonomy, // used to determine if existing object should be updated
  (t, o) => t.id.push(o.id), // operation for updating existing object
  ({ id, ...o }) => ({ ...o, id: [id] }) // return new object to insert
)

console.log(arr)


text:
Q: Google cast , what jar file are these located in? I am attempting to build and run an android google cast example. I can't seem to figure out which  jar these import are located in.
import com.google.android.gms.cast.ApplicationMetadata;
import com.google.android.gms.cast.Cast;
import com.google.android.gms.cast.Cast.ApplicationConnectionResult;
import com.google.android.gms.cast.CastDevice;
import com.google.android.gms.cast.CastMediaControlIntent;
import com.google.android.gms.common.api.ResultCallback;

A: these are part of Google Play Services library, you should download the latest one with the Android SDK Manager in ADT Tools
edit: they will be available in revision 15

A: Google Play Services, revision 15 is available now.


text:
Q: How can i add multiple values into one column in sql? i am creating app where you can register a person and then add it to list, next u can view this list with all info Name, Surname, Time, Date. But i dont know how to do it ? First of all i am countering a problem of sqlite exception that i cant set 4 values to one column. Secondly i dont know how to make custom list view where i can set Name is Item, Surname as subItem, in one column.
There is my Permission class, where i handle all edit text fields and button ok to add all strings to list.
  package com.example.pass;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class Permission extends ActionBarActivity{
 EditText Date;
 EditText Time;
 EditText userName;
 EditText userSurname;

 EditText Name;
 String Surname;

 //INITIALIZING THE VARIABLES...
 Button b1,b2;
 EditText e1;
 String text,u,text2,text3,text4;
 String un[]={"","","","","","","","","","","","","","",""};
 String pas;
 Cursor c;
 int i=0;
 String s,sqlquery;

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

    setContentView(R.layout.activity_permission);

    Button add = (Button) findViewById(R.id.add);
    Button cancel = (Button) findViewById(R.id.cancel);

    // Create custom dialog object
    // set values for custom dialog components - text, image and button
    userName = (EditText) findViewById(R.id.dialog_username);
    userSurname = (EditText)findViewById(R.id.dialog_usersurname);
    Time = (EditText)findViewById(R.id.dialog_time2);
    Date = (EditText)findViewById(R.id.dialog_date2);

           Date.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //To show current date in the datepicker
                    Calendar mcurrentDate=Calendar.getInstance();
                    int mYear = mcurrentDate.get(Calendar.YEAR);
                    int mMonth = mcurrentDate.get(Calendar.MONTH);
                    int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

                    DatePickerDialog mDatePicker=new DatePickerDialog(Permission.this, new OnDateSetListener() {
                        public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                            // TODO Auto-generated method stub
                            /*      Your code   to get date and time    */
                            Date.setText(selectedyear+"-"+(selectedmonth+1)+"-"+selectedday);
                        }
                    },mYear, mMonth, mDay);
                    mDatePicker.setTitle("Select date");
                    mDatePicker.show();  }
            });

           Time.setOnClickListener(new OnClickListener() {
               @Override
               public void onClick(View v) {
                   // TODO Auto-generated method stub
                   //To show current date in the datepicker

                   Calendar mcurrentTime=Calendar.getInstance();
                   int mHour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                   int mMinute = mcurrentTime.get(Calendar.MINUTE);

                   TimePickerDialog mTimePicker=new TimePickerDialog(Permission.this, new OnTimeSetListener() {
                       public void onTimeSet(TimePicker timepicker, int selectedhour, int selectedminute ) {
                           // TODO Auto-generated method stub
                           /*      Your code   to get date and time    */
                          if (selectedminute<10){
                              Time.setText(selectedhour+":"+"0"+(selectedminute)+""+"val");
                          }
                          else
                        Time.setText(selectedhour+":"+(selectedminute));
                       }
                   },mHour, mMinute, false);
                   mTimePicker.setTitle("Select date");
                   mTimePicker.show();  }
           });

          cancel.setOnClickListener(new OnClickListener() {
               @Override
               public void onClick(View v) {
                   // TODO Auto-generated method stub
                   //To show current date in the datepicker
                    startActivity(new Intent(Permission.this, Choose.class));
                  Permission.this.finish();
               }
           });

          add.setOnClickListener(new OnClickListener() {
              @Override
              public void onClick(View arg0) {
                  // TODO Auto-generated method stub
                  text=userName.getText().toString();
                  text2=userSurname.getText().toString();
                  text3=Date.getText().toString();
                  text4=Time.getText().toString();
                  //CREATING A DATABASE OBJECT..HERE db is SQLITEDATABASE OBJECT AND
                  // todo is our database name AND
                  //WE ARE USING IT IN WRITE MODE
                  SQLiteDatabase db=openOrCreateDatabase("todo", Context.MODE_WORLD_WRITEABLE, null);

                  text="'"+text+"'";
                  text2="'"+text2+"'";
                  text3="'"+text3+"'";
                  text4="'"+text4+"'";

          //SQL QUERY TO CREATE TABLE
          s="CREATE TABLE if not exists TODOLIST"+" ("+ "list" +" VARCHAR(100)"+");";
                  db.execSQL(s);

                  // QUERY TO INSERT THE DATA INTO TABLE
                  sqlquery="INSERT INTO TODOLIST"+ " VALUES"+"("+text+","+text2+","+text3+","+text4+");";
                  db.execSQL(sqlquery);
                  userName.setText("");

                  Toast.makeText(getApplicationContext(), "TASK ADDED IN LIST", Toast.LENGTH_SHORT).show();
              }
          });

        }

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.permission, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

  }

this is my permission xml file.
  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

  <EditText
    android:id="@+id/dialog_username"
    android:hint="Name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

  </EditText>
  <EditText
    android:id="@+id/dialog_usersurname"
    android:hint="Surname"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
  </EditText>
  <EditText
    android:id="@+id/dialog_date2"
    android:hint="Enter date"
    android:focusable="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
  </EditText>
  <EditText
    android:id="@+id/dialog_time2"
    android:hint="Enter time"
    android:focusable="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
 </EditText>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Cancel" />

</LinearLayout>

   </LinearLayout>

this is my detail class, it handles list view with back and clear buttons, so in this place i want to make R.layout.simple_expandable_list_item_1 custom and i dont know how? As i said that Name will be Item, surname as subItem, and show them both in one column.
   package com.example.pass;

 import android.app.Activity;
 import android.content.Context;
 import android.content.Intent;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.AdapterView;
 import android.widget.AdapterView.OnItemLongClickListener;
 import android.widget.ArrayAdapter;
 import android.widget.Button;
 import android.widget.ListView;
 import android.widget.Toast;

 public class Detail extends Activity {

    Button b, clr;
    ListView lv;
    String query;
    Cursor c;
    String uns[] = { "", "", "", "", "", "", "","","",""};
    int i = 0;
    int t = 0;
    SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.detail);
            b = (Button) findViewById(R.id.btn);
            clr = (Button) findViewById(R.id.clear);
            lv = (ListView) findViewById(R.id.listView1);

            // Declaring arrayadapter to store the items and return them as a view
            final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_expandable_list_item_1, uns);

            db = openOrCreateDatabase("todo", Context.MODE_WORLD_READABLE, null);

            //READING THE DATA FROM THE TABLE TODOLIST AND SETTING IN AN      ARRAYADAPTER...HERE C IS A CURSOR...
            //WHICH POINTS TO A ROW..AND MOVE TO THE NEXT ROW....
            c = db.rawQuery("SELECT * FROM TODOLIST; ", null);
            i = 0;
            while (c.moveToNext()) {

                    uns[i] = c.getString(0);
                    i++;
            }
            t = i;

            lv.setAdapter(adapter);

            // clear all the data from table..
            clr.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub

                            db = openOrCreateDatabase("todo",     Context.MODE_WORLD_WRITEABLE,
                                            null);

                            //QUERY TO DELETE ALL THE DATA FROM TABLE
                            db.delete("TODOLIST", null, null);

                            db.close();

                            for (int j = 0; j < t; j++) {
                                    uns[j] = "";
                                    lv.setAdapter(adapter);
                            }

                    }
            });

            //GOING BACK TO MAIN ACTIVITY
            b.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub
                            startActivity(new     Intent(getApplicationContext(),
                                            MainActivity.class));
                    }
            });

    }

 }

detail activity xml file
  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

 <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back" />

    <Button
        android:id="@+id/clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear all" />

 </LinearLayout>

 <ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</ListView>

 </LinearLayout>

my list looks like that

and register fields

A: First of all, for SQLite, you need to create a table for your users, then you need 1 coulmn by element you want to put (1 for surname, 1 for name,...) except if you put in there something like a JSONObject containing your user.
For example:
This class  is a definition of your tables with it's fields
public final class SQLiteContract{

// this shouldn't be instantiate
public SQLiteContract(){}

public static abstract class UserContract implements BaseColumns {

    /*                              TableName                           */

    public static final String TABLE_NAME = "USER";

    /*                              Fields                             */

    public static final String COLUMN_NAME_NAME = "Name";
    public static final String COLUMN_NAME_SURNAME = "Surname";
    public static final String COLUMN_NAME_TIME = "Time";
    public static final String COLUMN_NAME_DATE = "Date";
}

You should use the 1st one for having 4 fields in the sqlite. if you prefer having only one you need to change that part
    public static final String COLUMN_NAME_NAME = "Name";
    public static final String COLUMN_NAME_SURNAME = "Surname";
    public static final String COLUMN_NAME_TIME = "Time";
    public static final String COLUMN_NAME_DATE = "Date";

Into
    public static final String COLUMN_NAME_USER_JSONOBJECT = "UserObject";

Then your SQLite should looks something like this for the first one
private void dbCreateUser(SQLiteDatabase db)
{
    SQL_CREATE_USER = "CREATE TABLE " + UserContract.TABLE_NAME + " (";
    SQL_CREATE_USER += UserContract._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,";

    SQL_CREATE_USER += UserContract.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP;
    SQL_CREATE_USER += UserContract.COLUMN_NAME_SURNAME + TEXT_TYPE + COMMA_SEP;
    SQL_CREATE_USER += UserContract.COLUMN_NAME_TIME + TEXT_TYPE + COMMA_SEP;
    SQL_CREATE_USER += UserContract.COLUMN_NAME_DATE_TOUR + TEXT_TYPE;
    SQL_CREATE_USER += " )";
}

and for the second one only like
private void dbCreateUser(SQLiteDatabase db)
{
    SQL_CREATE_USER = "CREATE TABLE " + UserContract.TABLE_NAME + " (";
    SQL_CREATE_USER += UserContract._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,";
    SQL_CREATE_USER += UserContract. COLUMN_NAME_USER_JSONOBJECT+ TEXT_TYPE;
    SQL_CREATE_USER += " )";
}

Be aware that this could might need some update depending on the way you wanna store datas (as INT/BLOB/TEXT and so on)
Also, the variable TEXT_TYPE and COMMA_SEP are these :
private static final String TEXT_TYPE = " TEXT";
private static final String INTEGER_TYPE = " INTEGER";
private static final String COMMA_SEP = ",";

Here is a Link to Google's tutorial for SQLite Databases
Then for the list view, you need to create a custom layout that will be shown in the listview, maybe you should give a look to that tutorial.