text:
Q: Google chart dots over dots value Working on a line google chart where I am going to have values which are not so big from eachother, maybe some decinals in difference. So now its making it difficult to mouseover each dots to see the value. Is it possible to make the value to show right next to the dot with the same color of the legend ? Or is it another better solution to this problem ? Here is how it looks now:

Code:
<?php

    $con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
    mysql_select_db("nih_bw", $con);

    $sth = mysql_query("
SELECT routines.date, routines.time,
SUM( IF( measurements.title =  'T_Temperatur', CAST( REPLACE( routines.value,  ',',  '.' ) AS DECIMAL( 18, 2 ) ), null ) ) AS Temperatur,

SUM( IF( measurements.title =  'T_Badende_per_Time', CAST( REPLACE( routines.value,  ',',  '.' ) AS DECIMAL( 18, 2 ) ), null ) ) AS Badende,

SUM( IF( measurements.title =  'T_Luft_Temperatur', CAST( REPLACE( routines.value,  ',',  '.' ) AS DECIMAL( 18, 2 ) ), null ) ) AS Luft

FROM routines
INNER JOIN measure_routine ON routines.id = measure_routine.routine_id
INNER JOIN measurements ON measure_routine.measure_id = measurements.id
GROUP BY routines.date, routines.time
ORDER BY routines.date, routines.time;

    ;");
//Select measurements.title, routines.value, routines.date, routines.time from routines, measure_routine, measurements Where routines.id=measure_routine.routine_id AND measure_routine.measure_id=measurements.id AND measurements.title='T_Badende_per_Time' order by routines.date, routines.time

    $rows = array();
    //flag is not needed
    $flag = true;
    $table = array();

    $table['cols'] = array(

    array('label' => 'routines.date' & 'routines.time', 'type' => 'datetime'),
   array('label' => 'Temperatur', 'type' => 'number'),
   array('label' => 'Badende', 'type' => 'number'),
   array('label' => 'Luft', 'type' => 'number'),

    );

    $rows = array();

    while($r = mysql_fetch_assoc($sth)) {
        $temp = array();
    // assumes dates are in the format "yyyy-MM-dd"
    $dateString = $r['date'];
    $dateArray = explode('-', $dateString);
    $year = $dateArray[0];
    $month = $dateArray[1] - 1; // subtract 1 to convert to javascript's 0-indexed months
    $day = $dateArray[2];

    // assumes time is in the format "hh:mm:ss"
    $timeString = $r['time'];
    $timeArray = explode(':', $timeString);
    $hours = $timeArray[0];
    $minutes = $timeArray[1];
    $seconds = $timeArray[2];

    $temp = array();
    $temp[] = array('v' => "Date($year, $month, $day, $hours, $minutes, $seconds)");
    $temp[] = array('v' => $r['Temperatur']);
    $temp[] = array('v' => $r['Badende']);
    $temp[] = array('v' => $r['Luft']);

    $rows[] = array('c' => $temp);

    }

    $table['rows'] = $rows;

    $jsonTable = json_encode($table, JSON_NUMERIC_CHECK);

     echo $jsonTable;

?>


text:
Q: Bullet symbol in TextView reverses/mirrors text in Android Preview Window API 18 I have a simple TextView in my layout. I want to add bullet symbol (to mark some of hidden text in it). Issue is that text is kind of reversed after adding bullet symbol. Example:
xml: android:text="•••• •••• ••••  1234"
preview window of API 18: "1234 •••• •••• ••••"
This happens on API 18 ( API 17 displays correctly). This happens only if there are no letters in textview.
What could be the cause and how can I fix this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: member variable is null after function return? I have a class that extends View. This class has the member variable mCanvas
private Canvas mCanvas;

This variable is created when the view is resized, so the appropriate sizes for the canvas are set:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    int curW = mBitmap != null ? mBitmap.getWidth() : 0;
    int curH = mBitmap != null ? mBitmap.getHeight() : 0;
    if (curW >= w && curH >= h) {
        return;
    }

    if (curW < w) curW = w;
    if (curH < h) curH = h;

    Bitmap canvasBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(canvasBitmap);
    if (mBitmap != null) {
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
    }
    mBitmap = canvasBitmap;
}

But in my onDraw function i'm getting a null pointer exception when i try get the width/height of my canvas. I was unsure when onSizeChanged is actually getting called, i was assuming it would always get called when the view was created and therefore before onDraw.
But if my onDraw starts with this:
@Override
protected void onDraw(Canvas canvas) {
    if (mBitmap != null) {
        if(mCanvas == null)
        {
            Log.d("testing","mCanvas is null"
        }

logCat always shows the message "mCanvas is null" when i reach onDraw.
So i changed the code so that if mCanvas is null when i read onDraw i just create it again:
private void resizeCanvas()
{
    int curW = mBitmap != null ? mBitmap.getWidth() : 0;
    int curH = mBitmap != null ? mBitmap.getHeight() : 0;

    if (curW >= this.getWidth() && curH >= this.getHeight()) {
        return;
    }

    if (curW < this.getWidth()) curW = this.getWidth();
    if (curH < this.getHeight()) curH = this.getHeight();

    Bitmap canvasBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(canvasBitmap);

    if (mBitmap != null) {
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
    }

    mBitmap = canvasBitmap;
}

@Override
protected void onDraw(Canvas canvas) {
    if (mBitmap != null) {
        if(mCanvas == null)
        {
            resizeCanvas();
            if(mCanvas == null)
            {
                Log.d("test","canvas is still null");
            }

logCat still prints "canvas is still null"
Can someone explain what is happening here? I'm very new with android and most of this code is from the touchpaint example that i've been playing with.
If i check inside the resizeCanvas function if mCanvas is null it always says it is not null. But if i check just after calling that function it is always null.

A: I think the problem is in your resizeCanvas as you can return from it before initializing mCanvas.


text:
Q: How to nulify one dimenstion in a cube I want to create a cube, but i want to have the option to nulify one dimention, so that it becomes two dimentional like a sheet of paper.
I tried this:
var cubeGeometry = new THREE.BoxGeometry(10, 0, 10);
var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xF7F7F7});
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

but it didnt work.
Even if i zero all the parameters of the cube, it is still a cube.

A: Can you just set the scale in one dimension to some small number like 0.00001?
(note: you can't set the scale to 0 because the normals will collapse)

html, body {
  margin: 0;
  height: 100%;
}
#c {
  width: 100%;
  height: 100%;
  display: block;
}
<canvas id="c"></canvas>
<script type="module">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/build/three.module.js';
import {OrbitControls} from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/examples/jsm/controls/OrbitControls.js';
import {GUI} from 'https://threejsfundamentals.org/threejs/../3rdparty/dat.gui.module.js';

function main() {
  const canvas = document.querySelector('#c');
  const renderer = new THREE.WebGLRenderer({canvas});

  const fov = 45;
  const aspect = 2;  // the canvas default
  const near = 0.1;
  const far = 100;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.set(0, 10, 20);

  const controls = new OrbitControls(camera, canvas);
  controls.target.set(0, 5, 0);
  controls.update();

  const scene = new THREE.Scene();
  scene.background = new THREE.Color('white');

  {
    const planeSize = 40;

    const loader = new THREE.TextureLoader();
    const texture = loader.load('https://threejsfundamentals.org/threejs/resources/images/checker.png');
    texture.wrapS = THREE.RepeatWrapping;
    texture.wrapT = THREE.RepeatWrapping;
    texture.magFilter = THREE.NearestFilter;
    const repeats = planeSize / 2;
    texture.repeat.set(repeats, repeats);

    const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize);
    const planeMat = new THREE.MeshPhongMaterial({
      map: texture,
      side: THREE.DoubleSide,
    });
    const mesh = new THREE.Mesh(planeGeo, planeMat);
    mesh.rotation.x = Math.PI * -.5;
    scene.add(mesh);
  }

  let cube;
  {
    const cubeSize = 4;
    const cubeGeo = new THREE.BoxBufferGeometry(cubeSize, cubeSize, cubeSize);
    const cubeMat = new THREE.MeshPhongMaterial({color: '#8AC'});
    cube = new THREE.Mesh(cubeGeo, cubeMat);
    cube.position.set(cubeSize + 1, cubeSize / 2, 0);
    scene.add(cube);
  }
  let sphere;
  {
    const sphereRadius = 3;
    const sphereWidthDivisions = 8;
    const sphereHeightDivisions = 4;
    const sphereGeo = new THREE.SphereBufferGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
    const sphereMat = new THREE.MeshPhongMaterial({color: '#CA8', flatShading: true});
    sphere = new THREE.Mesh(sphereGeo, sphereMat);
    sphere.position.set(-sphereRadius - 1, sphereRadius + 2, 0);
    scene.add(sphere);
  }
  let cube2;
  {
    const cubeSize = 4;
    const cubeGeo = new THREE.BoxBufferGeometry(cubeSize, cubeSize, cubeSize);
    const cubeMat = new THREE.MeshPhongMaterial({color: '#F48'});
    // by parenting to an object3d we can squish on some aribtrary axis
    cube2 = new THREE.Object3D();
    cube2.position.set(0, cubeSize * 2, 0);
    scene.add(cube2);
    const cube = new THREE.Mesh(cubeGeo, cubeMat);
    cube.rotation.set(0.7, 0.5, 0);
    cube2.add(cube);
  }
  const gui = new GUI();
  gui.add(sphere.scale, 'x', 0.0001, 1, .000001).name('sphere scale');
  gui.add(cube.scale, 'x', 0.0001, 1, .000001).name('cube scale');
  gui.add(cube2.scale, 'x', 0.0001, 1, .000001).name('cube2 scale');

  [
    [[-4, 90, 10], [-5, 0, 0]],
    [[ 3,  5,  4], [ 0, 9, 0]],
  ].map((pt) => {
    const color = 0xFFFFFF;
    const intensity = 1;
    const light = new THREE.DirectionalLight(color, intensity);
    light.position.set(...pt[0]);
    light.target.position.set(...pt[1]);
    scene.add(light);
    scene.add(light.target);
  });

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  function render(time) {
    time *= 0.001;

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
    }

    sphere.rotation.x = time;
    sphere.rotation.y = time;
    cube.rotation.x = time;
    cube.rotation.y = time;
    cube2.rotation.x = time;
    cube2.rotation.y = time;

    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }

  requestAnimationFrame(render);
}

main();
</script>


text:
Q: Computing render time for blender animation For a project I need to be able to estimate render time for a given blender file animation. I use Blender Python API for rendering.
To estimate the total render time I'm thinking to render a sample frame (for example first frame), measure the time it takes then multiply it by number of frames to get the total render time for that animation.
This approach is based on the assumption that render time for all the frames in an animation is about the same. Is that true or it varies across frames for example depending on what's in each frame?
Also if there is a better approach for estimating the total render time please let me know.


text:
Q: How to change the backgroundcolor of a cardview when it is selected? I already have something to tell me which card is selected but if I want to set the background color of the itemview it doesn't change my CardView it changes the background color of my RecyclerView at that spot.
//this method is binding the data on the list
override fun onBindViewHolder(holder: CustomAdapterExercise.ViewHolder, position: Int) {
    if (holder.itemViewType == typeAdd) {
        holder.bindAdd(addList[0])
    }
    else{
        if(position != exerciseList.size){
            holder.bindItems(exerciseList[position])
        }
    }

    if (selectedPosition == position && position != exerciseList.size) {
        holder.itemView.setBackgroundColor(Color.parseColor("#000000"))
    }
    else {
        holder.itemView.setBackgroundColor(Color.parseColor("#ffffff"))
    }

    holder.itemView.setOnClickListener {
        selectedPosition = position
        notifyDataSetChanged()
    }
}

A: Alright I found the answer myself, but for everyone who is struggling like I was here is the answer:
if (selectedPosition == position && position != exerciseList.size) {
        val card_view = holder.itemView.findViewById<CardView>(R.id.boxesExercise)
        card_view.setCardBackgroundColor(Color.parseColor("#d7263d"))
    }
    else {
        if(exerciseList.size != 0){
            val card_view = holder.itemView.findViewById<CardView>(R.id.boxesExercise)
            if(card_view != null){
                card_view.setCardBackgroundColor(Color.parseColor("#0197f6"))
            }

        }

    }

You can find the CardView with the ID through the holder.itemView, since the CardView is a Child of holder.itemView.
I was doing it wrong in my earlier attempts because I tried to apply the Backgroundcolor directly to the holder.itemView and not to the CardView.
Hope this helps someone!


text:
Q: Vertical scrollbar taking last column width I am using free jqgrid 4.14. I am having a problem with the vertical scrollbar in the tree grid.
I have defined a height for the tree grid. Now when the grids loads and I try to expand it this happens.

But as soon as I am resizing the window the scrollbar width is not taken from last column width instead it has it own. See

So, I thought of making load vertical scrollbar at start
.ui-jqgrid .ui-jqgrid-bdiv { overflow-y: scroll }

but then also it is taking width from the column.
I am loading grid with these settings -
    datatype: "jsonstring",
    datastr: grid_data,
    colNames: scopes.grid_header_column_value[grid_id],
    colModel: scopes.gridcolumns[grid_id],
    height: height,
    viewrecords: is_pager_enable,
    multiSort: true,
    ignoreCase: true,
    grouping: is_group_enable,
    headertitles:true,
    sortorder: sort_order,
    sortable: false,
    pager: "#" + pager_id,
    treeGrid: true,
    treeGridModel: 'adjacency',
    treedatatype: "jsonstring",
    ExpandColumn: 'name'

Also, I am applying these properties -
$("#" + grid_id).closest('.ui-jqgrid-bdiv').width($("#" + grid_id).closest('.ui-jqgrid-bdiv').width() + 1);
$(".ui-jqgrid-sortable").css('white-space', 'normal');
$(".ui-jqgrid-sortable").css('height', 'auto');
$(".ui-jqgrid tr.jqgrow td").css('white-space', 'normal');
$(".ui-jqgrid tr.jqgrow td").css('height', 'auto');
$("div.ui-jqgrid-sdiv").after($("div.ui-jqgrid-bdiv"));

I am  also using jqGridAfterLoadComplete event so that on loading also it performs the same operation which it should perform in resizing from here
So, how can force the vertical scrollbar to take width from outside of grid.
Update: Added image after the solution

Here is the image which specifies exactly what I want.
Here the scrollbar is not needed but still, it is initialized as empty without taking column width

Problem while resizing:
I am using jquery event when the window is resized so to resize the jqgrid according to the screen but here the problem is if I resize the window to smaller screen and expand the tree grid, scrollbar comes.
The code is for resizing is like this -
 $(window).bind('resize', function () {
         resizeGrid.call($('#' + grid_id));
        });

resizeGrid = function () {
        var newWidth = $(this).closest(".ui-jqgrid").parent().width();
        $(this).jqGrid("setGridWidth", newWidth, true);
        };

Like this -

here the scrollbar have extra space and it is coming outside the given space.
Also, now if I resize window to full size and collapse all the rows the empty is there for the scrollbar.
It looks like this -

A: Try to add the callback treeGridAfterExpandRow with the following code:
treeGridAfterExpandRow: function () {
    this.fixScrollOffsetAndhBoxPadding();
}

I'm not sure that I exactly understand, which behavior you need to have. Probably the usage of two callbacks treeGridAfterExpandRow and treeGridAfterCollapseRow
treeGridAfterExpandRow: normalizeWidth,
treeGridAfterCollapseRow: normalizeWidth

with normalizeWidth defined as
var normalizeWidth = function () {
        var $self = $(this), p = $self.jqGrid("getGridParam");
        this.fixScrollOffsetAndhBoxPadding();
        if (!p.autowidth && (p.widthOrg === undefined || p.widthOrg === "auto" || p.widthOrg === "100%")) {
            $self.jqGrid("setGridWidth", p.tblwidth + p.scrollOffset, false);
        }
    };

will more close to your requirements. The above code extend the width of the TreeGrid to the width of the scroll bar if the vertical scroll bar will be visible.


text:
Q: What do the plans for incorporating "new ways to say thanks" look like? A recent Tweet from @StackOverflow on Twitter said:

Announcing our new reactions feature, available today on Stack Overflow for Teams for Basic and Business tiers, and coming to Enterprise in 2020.
New ways of saying 'thanks' will be coming to the Stack Exchange network next year, too.

(emphasis added)

The emojis look like an SOS symbol, a party emoji, a highfive / plea (still unclear on that), and a "100".
For the benefit of users who aren't on Teams, what does this currently look like?
More importantly, what are the current plans for what this will look like when it hits the SE network? Will it be the same set of emojis? What will the rep requirements to use them be? Will people be able to see who reacted what or will they be anonymous? Will you get a notification for reactions? Is there a limit to how many you can use in a day? Are there badges related to either giving or receiving them?
What will these reactions look like when they hit the broader network?

A:
NOTE: a modified version, allowing only 'Thanks' as a reaction on answers, is currently being tested on the public Stack Overflow.

For the benefit of users who aren't on Teams, what does this currently look like?

I've added this information to the reactions tag wiki on Meta Stack Overflow:

For questions about reactions, canned responses in the form of icons ('celebrate', 'help', 'thanks' and '100') to posts on stack-overflow-for-teams.

The first screenshot is the popup you use to add a reaction to a post; the second one shows the current list of reactions.

Will people be able to see who reacted what or will they be anonymous?

Yes, see the second screenshot.

Will you get a notification for reactions?

No, you don't get notifications for them.

The above information is just to inform you how they currently look like. The tweet says

New ways of saying 'thanks' will be coming to the Stack Exchange network next year, too.

which could be interpreted as meaning that the networkwide feature will have roughly the same purpose, but it will be different than the Reactions feature on Stack Overflow for Teams.

A: Github added similar emoji "Reactions to Pull Requests, Issues, and Comments" a few years ago:
https://github.blog/2016-03-10-add-reactions-to-pull-requests-issues-and-comments/

This feature was specifically created in response to an issue raised in the "Dear GitHub" open letter sent by members of the GitHub / Open Source community:

https://github.com/dear-github/dear-github

*

*Issues often accumulate content-less "+1" comments which serve only to spam the maintainers and any others subscribed to the issue. These +1s serve a valuable function in letting maintainers know how widespread an issue is, but their drawbacks are too great. We'd like issues to gain a first-class voting system, and for content-less comments like "+1" or "" or "me too" to trigger a warning and instructions on how to use the voting mechanism.

In my experience these emoji have been hugely beneficial in GitHub PRs, issues, and comment threads - essentially a quick way to upvote/downvote a post, but also allowing you to express reactions such as "love" or "confused" or  "celebration".
There's less of an obvious immediate need on SE, where posts can already be upvoted/downvoted (or easily edited/deleted) to solve many of the same problems raised in the GitHub letter.

P.S. here was GitHub's response to the community open letter:

Dear Open Source Maintainers,
We hear you and we're sorry. We've been slow to respond to your letter and slow to respond to your frustrations.
We're working hard to fix this. Over the next few weeks we'll begin releasing a number of improvements to Issues, many of which will address the specific concerns raised in the letter. But we're not going to stop there. We'll continue to focus on Issues moving forward by adding new features, responding to feedback, and iterating on the core experience. We've also got a few surprises in store.
Issues haven't gotten much attention from GitHub these past few years and that was a mistake, but we've never stopped thinking about or caring about you and your communities. However, we know we haven't communicated that. So in addition to improving Issues, we're also going to kick off a few initiatives that will help give you more insight into what's on our radar. We want to make sharing feedback with GitHub less of a black box experience and we want to hear your ideas and concerns regularly.
We'll be in touch next week. Sorry it's taken so long, and thank you for everything.
—GitHub

A: I think those ways of conveying thanks aren't worth the bytes it takes to record them, because they don't say much more than "thanks", which is what an up vote does.
But that does not mean a systematic or structured means for communicating a more nuanced way of saying "thanks" might not be useful. In theory, although I am mildly sceptical.
Perhaps something communicating why someone is thankful might be better. Like,

*

*"thanks, that saved me much time"

*"thanks, I learned something useful for the future"

*"thanks, I avoided a potential disaster"

*"thanks, you explained an important thing that is  elsewhere obscured by technical details and jargon"

Why would that be better? Because a structured means  might at a glance  communicate to potential readers why they might want to read the post. It might also save them time, teach them, enable them to avoid a disaster, and so on. Being able to see something about the post at a glance is the benefit over recording thanks in free form comments. If posts can be sorted or filtered by reactions, they could also help with searching in a way that thanks in comments can't.


text:
Q: Spring Dependency Injection usage I'm still learning about the Spring Framework and I'm trying to really get a good understanding of when and how to use Dependency Injection
Should all dependencies be managed via Interfaces?

A: Use interfaces for dependencies that expose an API of some sort and that have an implementation that may need to be swapped out (e.g. using mocks in unit tests). One common case is the DAO (data access object), which in Spring Data refers to as a Repository, which ties your data model to a persistence layer. Another common case is a Service which exposes operations on your domain model. Typically a Service will depend on the data access layer, so to unit test the service you will mock the DAO/repository. Another example is a third-party service; these are often only used by production systems, but must be simulated in development and testing environments. In this case, an interface is far superior to, say, embedding boolean flags in your code and hoping you don't have any logic errors.
The key thing to remember about managing dependencies is actually managing your use of the new keyword. Any time you use new, you are creating a dependency on an implementation. The goal of dependency injection is to separate how you use things you depend on with how you get them. You can depend on either an interface or a class, for a simple, obvious reason: Java supports subclassing. So even if you depend on a class instead of an interface, you might end up with a subclass. Spring framework actually does this automatically in many cases.
If you find yourself needing to create objects and you're not sure that you should depend on them, have your dependency injection framework give you a Factory for those objects. How this works is obviously framework-dependent, but all frameworks that I know of support factories. If you're not using a framework, you can still write factories and use them instead of using new all the time.

A: If you write a code without using spring IOC container, you have to write some factory classes to create objects and hook them up. For an example instance consider a service class which has a reference to the DAO instance. You have to write some initialization factory for the service class which guarantees a singleton access to the service class and makes sure that the service class is instantiated with an instance of DAO. Creating new instances everywhere in your code is not a good practice, hence factory pattern is used. But if you use Spring IOC container it will take care of all these things. Usually it creates singleton instances so you don't need to use new keyword in your code lending you to write more clear code. Your code is loosely coupled and more maintainable with this approach. If you have only one public constructor you can now have the liberty of doing a constructor injection, without using @Autowire invasive annotation with the new spring version.
There are three DI mechanisma used in spring as stated here. Out of the three constructor injection is recommended since it is more testable and does not lead to any invariant. Field injection using @Autowire is evil and not recommended since it is not testable solution.
Hope this helps. Happy coding.


text:
Q: I want if year(picklist) is selected then total investment(number) is display I have one requirement that if i select Year__c ( picklist) field then Total_INVESTMENT__C (NUMBER) is display.

A: Based on your question try this one in a formula field..VALUE(Text(Year__c ))


text:
Q: Doctrine 2 creating multiple records I am trying to create multiple records via Doctrine, and I am running into a strange problem where it will create the first record successfully, but no others. Say I have the following where Record is a Doctrine Entity and record_id is the primary key:
 $entityManager->getConnection()->beginTransaction();

 foreach($recordsToCreate as $data)
 {
   $record = new Record();
   $record->field1 = $data['field1'];
   $record->field2 = $data['field2'];

   $entityManager->persist($record);
   $entityManager->flush();
 }

 $entityManager->getConnection()->commit();

If I have three records, the first will be created correctly, but not the other two. No errors or exceptions are thrown, but the records are not being created in the database. If I output each record after the flush, all fields are set correctly but the primary key is null after the first record. I'm thinking this is a Doctrine glitch but I want to make sure before I submit a bug report.
Thanks.

A: Figured it out-the answer wasn't putting flush() outside the loop as stated above. The solution was to use detach() after committing the transaction. So:
 foreach($recordsToCreate as $data)
 {
   $entityManager->getConnection()->beginTransaction();
   $record = new Record();
   $record->field1 = $data['field1'];
   $record->field2 = $data['field2'];

   $entityManager->persist($record);
   $entityManager->flush();

   $entityManager->getConnection()->commit();
   $entityManager->detach($record);
 }

That works for me now. The problem was that somehow (I think) the entity manager couldn't tell the difference between the first record and the rest, so detach ensures that it always has a new record when it's doing a create. Also, the transaction is in the loop now since I'm actually creating/modifying other records with this one in my actual code, so having it inside the loop is more accurate to my setup.
so In a nutshell, call detach on the new record after the commit and it's all good for me.


text:
Q: How to add extra text to input value result using jQuery My html form is:
<form id="search" action="form.html" method="get">
    <input type="text" id="keyword" name="search" placeholder="keywords" />
</form>

When type "test" and hit enter, it will go to form.html?search=test
Using jQuery, how can I add "xx-" on the result, i.e. form.html?search=xx-test ?
Thank you

A: I hope this helps:
$("#search").submit(function(event) {
  var $form = $( this ),
      url = $form.attr( 'action' );
  var submitdata = $.get( url, { search: "xx-" + $('#keyword').val()} );

  submitdata.done(function( data ) {
    alert('success');
  });
});

A: Use keypress to catch enter event and make your url to redirect like this.
$('#keyword input').bind('keypress', function(e) {
    if(e.keyCode==13){
        var keyword= $('#keyword').val();
        window.location = form.html?search=xx_' + keyword;
    }

});

A: You can stop the submission of the form, and construct the URL by yourself.
<form id="search" action="form.html" method="get">
    <input type="text" id="keyword" name="search" placeholder="keywords" />
</form>
<script>
$("#search").submit(function(e) {
  e.preventDefault();
  var url = this.attr('action')
  url += '?keyword=xx-' + encodeURIComponent($('#keyword').val());
  location.href = url;
});
</script>


text:
Q: How to retrieve data from multiple daily tables in SQL Server I am new to Microsoft SQL Server 2008. I need some help in retrieving data from multiple tables which have same columns with same datatype.
Currently I have multiple tables in my database, each table contains data for a single day. For example, I have the following tables:

*

*Table_20160820

*Table_20160821

*Table_20160822

*Table_20160823

*Table_20160824

*Table_20160825

All the tables have same columns with same datatype say:

*

*column_1

*column_2

*column_3

*column_4

Now, is it possible to retrieve the columns from all the tables using a single query.
What I am exactly looking for is to get the count of column_3 which will be grouped by column_1 for all the tables. I want to avoid writing multiple queries as I need to fetch the data for an entire month i.e. from 30 tables.

A: As the comments have said, it'd be best to organize this into a single table, and then add a date column so you can see when each row was added.  You can even set the default value of the date_created column to be getdate().
To get all of the data together use the UNION Operator in conjunction with an insert statement to your new better table.
CREATE TABLE Better_Table (Column_1 <type>, Column_2 <type>, ..., Date_Created DateTime2(7) Default GETDATE())
GO
INSERT INTO Better_Table (Column_1, Column_2, ...)
SELECT *, '2016/08/22' FROM Table_20160822
UNION
SELECT *, '2016/08/23' FROM Table_20160823
...

Once you've done this your query will be far simpler:
SELECT Column_1, COUNT(Column_3)
FROM Better_Table
WHERE date_created >= '2016/08/01'
AND date_created < '2016/09/01'
GROUP BY Column_1

Although you can still do this in the db current state by using the union operator in the group by query.  It would look something like this:
SELECT a.column_1, COUNT(a.column_3)
FROM (
SELECT column_1, Column_3
FROM Table_20160822
UNION ALL
SELECT column_1, Column_3
FROM Table_20160823
) a
GROUP BY a.Column_1

Just expand this to the tables you need to grab from.

A: You can use CTE to get all dates you need, then create a query and execute it:
DECLARE @dateStart datetime = '2016-08-01',
        @dateFinish datetime = '2016-09-01',
        @query nvarchar(max)

;WITH cte as (
SELECT  @dateStart as d
UNION ALL
SELECT DATEADD(day,1,d)
FROM cte
WHERE DATEADD(day,1,d) < @dateFinish
)

SELECT @query = (

    SELECT 'SELECT column_1, COUNT(column_3) FROM ( '
    + STUFF((
    SELECT  ' UNION ALL SELECT * FROM [Table_'+CONVERT(nvarchar(8),d,112)+'] '
    FROM cte
    FOR XML PATH('')
    ),1,10,'') + ') as t GROUP BY column_1 '
    FOR XML PATH('')
)

PRINT @query

EXEC sp_executesql @query

Output of @query variable:
SELECT column_1, COUNT(column_3)
FROM (
    SELECT * FROM [Table_20160801]  UNION ALL
    SELECT * FROM [Table_20160802]  UNION ALL
    SELECT * FROM [Table_20160803]  UNION ALL
    SELECT * FROM [Table_20160804]  UNION ALL
    ....
    SELECT * FROM [Table_20160831]
) as t
GROUP BY column_1

A: As mentioned above this is a bad design and it would be good if the design is fixed at first place. This is a technical debt which has to be paid back sooner or later. Anyway here's how you can do it:
DECLARE @dtStartDate        DATE,
        @dtEndDate          DATE,
        @nvchTablePrefix    NVARCHAR(50),
        @nvchQuery          NVARCHAR(max)

SELECT  @dtStartDate = '20160801',
        @dtEndDate = '20160831',
        @nvchTablePrefix = 'Table_'

CREATE TABLE #temp
(name NVARCHAR(100))

WHILE(@dtStartDate <= @dtEndDate)
BEGIN
INSERT INTO #temp
SELECT  ' SELECT column_1, column_3 FROM ' + @nvchTablePrefix +    CONVERT(NVARCHAR,@dtStartDate,112)

SELECT @dtStartDate = DATEADD(d,1,@dtStartDate)

IF (@dtStartDate <= @dtEndDate)
INSERT INTO #temp
SELECT  ' UNION '
END

SELECT @nvchQuery = 'SELECT column_1, COUNT(column_3) as column3count FROM ( '

SELECT @nvchQuery = @nvchQuery + name FROM #temp

SELECT @nvchQuery = @nvchQuery + ') t GROUP BY column1'

PRINT @nvchQuery
EXEC sp_executesql @nvchQuery

DROP TABLE #temp

OUTPUT of print statement will be like -
 SELECT column_1, COUNT(column_3) as column3count
 FROM
 (   SELECT column_1, column_3 FROM Table_20160801
     UNION
     SELECT column_1, column_3 FROM Table_20160802
     UNION
     ....
     UNION
     SELECT column_1, column_3 FROM Table_20160831
 ) t GROUP BY column1


text:
Q: ON CONFLICT DO UPDATE command cannot affect row a second time when trying to pass additional columns from a CTE in postgresql Based on the SO: https://dba.stackexchange.com/a/46477 answer provided, I have been extending the Function with UPSERT in Postgres 9.5 or later for my own purposes to insert data into multiple referenced tables.
I have the following type that I am passing to the function:
CREATE TYPE symbol_record AS
(
    name                       character varying(32),
    exchange                   character varying(64),

    base_name                  character varying(16),
    base_precision             smallint,
    base_commission_precision  smallint,

    quote_name                 character varying(16),
    quote_precision            smallint,
    quote_commission_precision smallint
);

the following relevant CTE's:
-- select all the distinct base_name and quote_name
typ_asset AS (SELECT v.name, a.id
    FROM (
        SELECT DISTINCT (base_name) name FROM val
        UNION
        SELECT DISTINCT (quote_name) name FROM val
    ) v
    LEFT JOIN asset a USING (name)
),

and
ins_asset AS (INSERT INTO asset AS a (name, created_at)
    SELECT name, now()
    FROM typ_asset
    WHERE id IS NULL
    ON CONFLICT (name) DO UPDATE
        SET name = EXCLUDED.name
            WHERE a.name <> EXCLUDED.name
    RETURNING a.name, a.id
),

are working correctly.
However, I am unsure how to return the matching 'precision' and 'commission_precision' columns for each of the base/quote for consumption by the calling insert/select in ins_asset.
I tried:
typ_asset AS (SELECT v.name, v."precision", v.commission_precision, a.id
    FROM (
        SELECT DISTINCT (base_name) name, (base_precision) "precision", (base_commission_precision) commission_precision FROM val
        UNION
        SELECT DISTINCT (quote_name) name, (quote_precision) "precision", (quote_commission_precision) commission_precision FROM val
    ) v
    LEFT JOIN asset a USING (name)
),

and adding the columns accordingly to the ins_asset CTE, but am getting the error:
ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time
I am currently using Postgres 14, and the tables and full function can be seen at:
https://dbfiddle.uk/?rdbms=postgres_14&fiddle=bfcb7f7a9a9fcbd8a1b65ec033af8ac2
I am sure it has something to do with the inserting additional data into the asset table (typ_asset / ins_asset) ctes, as it works fine without passing the additional columns (or I am passing them back incorrectly)
And further, yes I am fully aware that I am using a reserved keyword (precision). As this is the business language/terminology I have kept it for now (quoting as necessary), but it will also be fixed.
What is the correct way to return the 'precision' and 'commission_precision' columns, and upsert them into the asset table?  The 'name' column in the asset table is unique, and I have tried to set commission_precision instead of name in case the unique column was the cause of the error. that also failed with the same error.
edit
(1) per requested by ypercubeᵀᴹ, the full working fiddle without the precision and commission_precision values in the asset table:
https://dbfiddle.uk/?rdbms=postgres_14&fiddle=9f7ad113c6c812c1348bbc85eef24661
(2) I'm sorry, yes you are correct, I have been trying many different things to fix the problem and DISTINCT ON was one thing I tried (because I don't fully understand the language), apparently, among several other changes.  I have corrected the non working dbfiddle, and that actually fixed the problem.

A: The problem like due to the subquery:
FROM (
    SELECT DISTINCT (base_name) name, (base_precision) "precision", (base_commission_precision) commission_precision FROM val
    UNION
    SELECT DISTINCT (quote_name) name, (quote_precision) "precision", (quote_commission_precision) commission_precision FROM val
) v

producing rows with same name but different precision or commission_precision.
You'll need to fix it so it produces only one row for each name - according to your requirements. There may be different cases:

*

*rows with same base_name but different base_precision/base_commision_precision.

*rows with same quote_name but different quote_precision/quote_commision_precision.

*rows where base_name matches quote_name of other rows (and different precision/commision_precision).

Other points:

*

*the columns do not need to be in parantheses.

*the following code part looks to be doing totally nothing:
  ON CONFLICT (name) DO UPDATE
      SET name = EXCLUDED.name
          WHERE a.name <> EXCLUDED.name


text:
Q: How can I change the image in the detail view to access the master view I'm new with iOS development so I was wondering if there is any way to change the image "<" that I got in the detail view in an application Master-Detail for iOS? I'm using Xcode 7 beta and Swift.
Also, is there any way to prevent the master from filling all the screen when I tap to open it?
Image illustrate the image that I want to customize


text:
Q: Using CONVERT_TZ causes Perfomance issues? We are planning if either to change the timezone of the whole database or using CONVERT_TZ in all our functions and events.
Is there any perfomance issues is we decide to use CONVERT_TZ having in mind it could be converting and comparing millions of rows and events every minute?

A: It really depends where you plan to use the CONVERT_TZ function.
For example, if it's wrapped around a column in a WHERE clause, that will disable MySQL ability to use an index range scan operation. And that could have significant performance implications, or cause "performance issues".
For example, if this query is making use an index range scan on an index with mydatetime as the leading column, picking just a few needles out of a big haystack:
 SELECT t.foo
   FROM my_huge_table t
  WHERE t.mydatetime >= '2018-10-09 14:30'
    AND t.mydatetime <  '2018-10-09 15:15'

Adding CONVERT_TZ function around the literals won't cause performance issues. The performance will be the same:
 SELECT t.foo
   FROM my_huge_table t
  WHERE t.mydatetime >= CONVERT_TZ('2018-10-09 08:30','EST5EDT','UTC')
    AND t.mydatetime <  CONVERT_TZ('2018-10-09 09:15','EST5EDT','UTC')

But if we wrap the columns in the WHERE clause in a function, that will force MySQL to evaluate the function and then do the comparison, and it's going to do that for every row in the table.
Do NOT do this:
 SELECT t.foo
   FROM my_huge_table t
  WHERE CONVERT_TZ(t.mydatetime,'UTC','EST5EDT') >= '2018-10-09 08:30'
    AND CONVERT_TZ(t.mydatetime,'UTC','EST5EDT') <  '2018-10-09 09:15'

As long as the SQL still references bare columns in the predicates (conditions in the WHERE clause and ON clause), then adding CONVERT_TZ functions in other places in the SQL shouldn't cause a significant performance impact.


text:
Q: Wait for react state/props to update before using data? I am using react-redux with persist-store in my react app. Once the user logs in, the state contains user data i want to use to customize the app and display their name and other info. It works ok unless someone refreshes the page.
I added persist store because i would lose the state values on a refresh and it would show not authenticated. Now it works but there seems to be a delay before the state gets restored. So if i try to use the user's name in a component, on a refresh it will crash saying it is undefined. But after a few secs the data is available as i can see it in the console.log(this.props)
Right now i am using ternary operators for all these values and it's an ok solution but i was wondering if there is a way to wait for the data before it get's used?
Here's one of my component
TabContainer.propTypes = {
  children: PropTypes.node.isRequired,
};

class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: '',
      value: 0,
    };
  }

  componentDidMount() {
    const { fetchData } = this.props;
    fetchData(data);
  }

  handleChange = (event, value) => {
    this.setState({ value });
  };

  render() {
    const { login } = this.props;
    const title = brand.name + ' - Profile';
    const description = brand.desc;
    const { dataProps, classes } = this.props;
    const { value } = this.state;
    const name = login.user.name === undefined ? '' : shortenName(login.user.name);
    const group = login.user.groups === undefined ? '' : login.user.groups[0].name;
    const role =
      login.user.role === undefined
        ? ''
        : login.user.role.charAt(0).toUpperCase() + login.user.role.slice(1);

    return (
      <div>
        <Helmet>
          <title>{title}</title>
          <meta name="description" content={description} />
          <meta property="og:title" content={title} />
          <meta property="og:description" content={description} />
          <meta property="twitter:title" content={title} />
          <meta property="twitter:description" content={description} />
        </Helmet>
        <Cover
          coverImg={bgCover}
          avatar={dummy.user.avatar}
          name={name}
          desc={`${user.role.charAt(0).toUpperCase() + user.role.slice(1)} - ${group}`}
        />
        <AppBar position="static" className={classes.profileTab}>
          <Hidden mdUp>
            <Tabs
              value={value}
              onChange={this.handleChange}
              variant="fullWidth"
              indicatorColor="primary"
              textColor="primary"
              centered
            >
              <Tab icon={<AccountCircle />} />
              <Tab icon={<SupervisorAccount />} />
              <Tab icon={<Favorite />} />
              <Tab icon={<PhotoLibrary />} />
            </Tabs>
          </Hidden>
          <Hidden smDown>
            <Tabs
              value={value}
              onChange={this.handleChange}
              variant="fullWidth"
              indicatorColor="primary"
              textColor="primary"
              centered
            >
              <Tab icon={<AccountCircle />} label="ABOUT" />
              <Tab icon={<SupervisorAccount />} label="0 CONNECTIONS" />
              <Tab icon={<Favorite />} label="0 FAVORITES" />
              <Tab icon={<PhotoLibrary />} label="0 ALBUMS" />
            </Tabs>
          </Hidden>
        </AppBar>
        {value === 0 && (
          <TabContainer>
            <About data={dataProps} />
          </TabContainer>
        )}
        {value === 1 && (
          <TabContainer>
            <Connection />
          </TabContainer>
        )}
        {value === 2 && (
          <TabContainer>
            <Favorites />
          </TabContainer>
        )}
        {value === 3 && (
          <TabContainer>
            <Albums />
          </TabContainer>
        )}
      </div>
    );
  }
}

UserProfile.propTypes = {
  login: PropTypes.object.isRequired,
  classes: PropTypes.object.isRequired,
  dataProps: PropTypes.object.isRequired,
  fetchData: PropTypes.func.isRequired,
};

const reducer = 'socmed';
const mapStateToProps = state => ({
  force: state, // force state from reducer
  dataProps: state.getIn([reducer, 'dataTimeline']),
  login: state.get('login'),
});

const constDispatchToProps = dispatch => ({
  fetchData: bindActionCreators(fetchAction, dispatch),
});

const UserProfileMapped = connect(
  mapStateToProps,
  constDispatchToProps,
)(UserProfile);

export default withStyles(styles)(UserProfileMapped);

A: A couple ways to achieve this:

*

*Continue with your current approach, as using conditionals in render() is a valid and idiomatic way to display data in React.

*If fetchData returns a promise, keep track of a loading state, and don't render anything until the promise completes.

constructor(props) {
   super(props);
   this.state = {
      email: '',
      value: 0,
      isLoading: true,
   };
}

componentDidMount() {
   const { fetchData } = this.props;
   fetchData(data)
      .then(() => {
         this.setState({isLoading: false})
      })
      .catch((e) => {
         console.error(e);
         this.setState({isLoading: false})
      });
}

render() {
   const {isLoading} = this.state;

   if (isLoading) {
      return null;
   }

   ...
   // Remove the conditional around user
   ...
}


text:
Q: How to update a bulk selection of fields using field calculator in QGIS 2.8.1 I have an attribute table showing vegetation communities.  The table has three columns ("ID", "Veg Comm" and "Area_ha".  Instead of having to copy and paste text after each polygon created into each field (i.e. coastal wattle scrub), is there a way to highlight a selection and mass copy?

A: Yes, in the recent versions of QGIS, if you have a selection the 'Only update x selected features' checkbox is enabled as default. Any expression written will be updates to the chosen column of the selected rows. Below picture is from QGIS 2.8.1.

A: It's not a direct answer to your question as you are looking for a post-processing step, but as you say that you will do this step "after each polygon created into each field" you may be interested in the setting Setting > Options > Digitizing > Reuse laste entered attribute values. This will set the previously used attribute values as default while digitizing and may therefore remove the need for a post-processing step at all.


text:
Q: Handle a request with a specific function in a component We are developing a component that handles OpenID Connect's implicit flow.
In step 5 of the flow, the "Authorization Server sends the End-User back to the Client with an ID Token and, if requested, an Access Token."  We would like our component to handle that request, which will be to ~/openid-login.
How do we configure Aurelia to have it route to a function in our component?
export class OpenId {

    // how do we route ~/openid-login to this?
    public handleRequest() {

    }

}

Note: Here is the work in progress.

A: Using a navStrategy within your routeConfig will allow you to do what ever you like before navigating to a page. See below:
import { autoinject } from 'aurelia-framework';
import { RouterConfiguration, Router, NavigationInstruction } from 'aurelia-router';

@autoinject
export class App {

    router: Router;

    configureRouter(config: RouterConfiguration, router: Router) {

        let openIdNavStrat = (instruction: NavigationInstruction) => {

            console.log('Do whatever we would like to do.');

            // then redirect to where ever you would like.
            instruction.config.moduleId = 'login';
        }

        config.map([
            { route: ['', 'login'], moduleId: 'login' },
            { route: 'openid-login', navigationStrategy: openIdNavStrat },
        ]);

        this.router = router;
    }
}

There is documentation on Navigation Strategies here: http://aurelia.io/hub.html#/doc/article/aurelia/router/latest/router-configuration/3


text:
Q: Android System.loadLibrary crash in libhoudini (ARM translator on x86) My .so JNI library causes Android application to crash at loading time (call to System.loadLibrary) when ran on x86 Android. On ARM it's working fine.
The error in logcat is:
houdini﹕ [12251] Unsupported feature (ID:0x20e00149).
Houdini is an ARM translator for x86, so probably I'm using something that cannot be translated.
Obviously I can modify the code of my .so library co maybe I can change whatever the problem is, but how to investigate that? How could I know what part of my code is causing the problem?
Oh, and by the way - is any code from .so ran at loading time? Maybe some variable initializers?

A: a bit of internet search show that libhoundini is proprietary code (ask the vendor for support)
but yea, like all java native libraries,
it would probebly have a onload function.
something like: JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)
so, probebly it is what is causing the problem, because it is executed when the library is loaded.


text:
Q: appium : not able to retrieve TextView child element from parent ScrollView I am trying to find all TextView  elements of ScrollView. I tried following but it is not helping:
List<AndroidElement> el1 = driver.findElements(By.xpath("//android.widget.ScrollView/*"));

and
List<AndroidElement> el1 = driver.findElements(By.xpath("//android.widget.ScrollView/android.widget.TextView"));

I also tried to find element by xpath inside an element but it gives exception as it is not supported by appium.
Is there any other way to get the child elements ?

A: You can try this one if u want
WebElement parentElement=driver.findElement(by.className("android.widget.ScrollView"));

List<WebElement> childElements = parentElement.findElements(By.className("android.view.View"));


text:
Q: MockingKernel and Received throws an NotASubstituteException I'm using NSubstituteMockingKernel in order to build all my dependencies of my library classes. I've been struggling to solve a trouble for a week and I'm really exhausted. I need some help.
This is my class:
class Core : ICoreService, ICore {
    private ICoreConfiguration configuration;

    Core(ICoreconfiguration configuration) {
        this.configuration = configuration;
    }

    override ICoreService.ParentMethod() {   //ICoreService implementation
        foreach (Item item in this.configuration.Items)
            this.ChildMethod();
    }
    virtual ChildMethod() {
      //do something
    }
}

ICoreService is:
interface ICoreService {
    void ParentMethod();
}

ICore is:
interface ICore {
    ICoreConfiguration Configuration { get; }
}

ICoreConfiguration is:
interface ICoreConfiguration {
    IEnumerable<Item> Items { get; }
}

My test is:
[TestFixture]
public class UsersManagementTests
{
    private readonly NSubstituteMockingKernel IoCKernel;

    public UsersManagementTests()
    {
        this.IoCKernel = new NSubstituteMockingKernel();
    }

    [SetUp]
    public void SetUp()
    {
        this.IoCKernel.Reset();
    }

    [Test(Description = "Configured Users are well loaded on Kernel")]
    public void InitializationWithUsersTest()
    {
        //Setup Data
        Item item = Item.Create("item1");
        IEnumerable<Item> items = new List<Item>() { item };

        //Setup Mocks
        this.IoCKernel
            .Get<ICoreConfiguration>()
            .Items
                .Returns(items);
        Core core = this.IoCKernel.Get<Core>();

        //Act
        kernel.ParentMethod();

        //Assert
        IEnumerable<NSubstitute.Core.ICall> calls = kernel.ReceivedCalls(); // ((((((1))))))
        kernel.Received(1).ChildMethod();                                                    // ((((((2))))))
    }
}

When ((((((1)))))) or ((((((2)))))) are reached, I'm getting this NSubstitute.Exceptions.NotASubstituteException exception message now on last line:

NSubstitute extension methods like .Received() can only be called on objects created using Substitute.For() and related methods.

As you can see I'm trying to test ChildMethod method is reached once at least. ChildMethod must be called according to my Core.Kernel implementation.
I will really appreciate some help.
Thanks.


text:
Q: Function should return Promise, apparently returns Promise but still compiles Here's a small boildown of weird code I came across. I have fixed it but I don't understand why it was compiling:
const stringOrNull: () => Promise<string | null> = () =>
  Promise.resolve(Math.random() < 0.5 ? "Hello, world." : null);

// why does this compile?
const stringOrNullWeird: () => Promise<string> = () =>
  new Promise(resolve =>
    stringOrNull().then(result => resolve(result ? result : undefined))
  );

// will eventually crash with
// (node:20784) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'toLocaleLowerCase' of undefined
[...Array(10).keys()].forEach(async () =>
  console.log((await stringOrNullWeird()).toLocaleLowerCase())
);

I rewrote the function by simply placing the returned Promise inside a temporary variable so I could check the type inferred by TypeScript: it appears to be unknown and then the function does not compile.
// does not compile, as expected
// Type '() => Promise<unknown>' is not assignable to type '() => Promise<string>'.
//   Type 'Promise<unknown>' is not assignable to type 'Promise<string>'.
//     Type 'unknown' is not assignable to type 'string'.ts(2322)
const stringOrNullUnknown: () => Promise<string> = () => {
  // const p: Promise<unknown>
  const p = new Promise(resolve =>
    stringOrNull().then(result => resolve(result ? result : undefined))
  );
  return p;
};

So I don't understand how that second form is different from one above, and why the one above compiles, breaking type safety?

A: Actually the reason is not that Promise<unknown> was assignable to Promise<string>. When you assign a new Promise to where an Promise<string> is expected, TS will figure out new Promise(..) is really new Promise<string>(...). When you put it in a variable as in your second example, then TS has nowhere to figure out what the type parameter is and goes with unknown.
The real reason is this is allowed is that this is the signature for the Promise constructor:
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;

Notice that for resolve, value is optional, so undefined is an acceptable value. This issue says it fixes but then the changes were reverted due to this having unforeseen consequences in other places as described here
I would recommend avoiding the Promise constructor in general though:
const stringOrNullWeird: () => Promise<string> = () =>
  stringOrNull().then(result => result ? result : undefined);

The above is simpler and would have been an error.
Or if your async logic gets too complex use async/await:
const stringOrNullWeird: () => Promise<string> = async () => {
  const result = await stringOrNull()
  return result ? result : undefined;
}

Both would have been errors. Calling the Promise constructor is generally redundant.


text:
Q: codeigniter sessions not storing cross pages I haven't been able to find the answer to this, and I have searched + read the docs, I have tried many of things. Nothing seems to work. So I come here finally giving up on the search, hoping someone can give me an intelligent answer for a change, maybe something that can help me solve me under lying issue.
Having played with everything accordingly and not so accordingly I have come to the conclusion that there is no equivilant to PHP's "session_start()" running anywhere within my install of CI, this is a core install also. That said.. I know sessions work on my server as I have tried non-ci specific how php.net says to do it.. and they hold just fine.
any takers on what the issue is? Sorry if I sound arrogant above, im just tired, and even more tired of someone telling me "its not right" cause that part I figured out on my own.. and coming to forums I'd hope for help to debunk my issue and get on track not some bs answers..
well thanks all for taking in my rant/question
-frustrated..

A: Well, as you've already figured out - CodeIgniter's Session library doesn't actually use PHP sessions. I haven't really used it, but I think it's their own cookie-only based implementation.
So if you're trying to use the $_SESSION variable - it will not work. If you want to use it I'd suggest you extend the core CI_Controller class (that's easy and well-documented, if you haven't done it) and call session_start() in the constructor of your new Controller class. I personally prefer this, combined with my own sessions handler that uses a database for storage.


text:
Q: Split huge CSV by columns with Miller I need to split huge (>1 Gb) CSV files containing 50K+ columns each on a daily basis.
I've found Miller as an interesting and performant tool for such a task.
But I'm stuck on Miller's documentation.
How could I split one CSV to N smaller CSV files where N is a number of rows in my source file?

A: try with this script
mlr --csv put -S 'if (NR % 10000 == 0) {$rule=NR} else {$rule = ""}' \
then fill-down -f rule \
then put -S 'if ($rule=="") {$rule="0"}' \
then put -q 'tee > $rule.".csv", $*' input.csv

Make a copy of your CSV in a new folder, and then run this script on it.
It will produce a csv file for every 10000 rows.

A: the answer from aborruso does add a new column rule to the output csv files.
If you want to avoid this, use emit with mapexcept instead of tee in the last step, like this:
mlr --csv put -S 'if (NR % 10000 == 0) {$rule=NR} else {$rule = ""}' \
then fill-down -f rule \
then put -S 'if ($rule=="") {$rule="0"}' \
then put -q 'emit > $rule.".csv", mapexcept($*, "rule")' input.csv


text:
Q: Mysql Table creation from Mysql workbench to phpmyadmin Hi i had the following table structure on mysql workbench for a table example_1
But because of some reasons i want to recreate all the tables in phpmyadmin with the create table sysntax like below
Create table code in MYSQL workbench:
CREATE TABLE `example_1` (
  `job_id` int(11) NOT NULL AUTO_INCREMENT,
  `source_id` int(11) DEFAULT NULL,
  `publication_id` int(11) DEFAULT NULL,
  `facility_id` int(11) DEFAULT NULL,
  `job_type_id` int(11) NOT NULL,
  `template_id` int(11) DEFAULT NULL,
  `account_num` varchar(9) DEFAULT NULL,
  `start_dt` datetime DEFAULT NULL,
  `end_dt` datetime DEFAULT NULL,
  `pdf_path` varchar(20) DEFAULT NULL,
  `admin_user_id` int(11) NOT NULL,
  `skills` varchar(255) DEFAULT NULL,
  `tracking_pixel` varchar(255) DEFAULT NULL,
  `auto_renew` smallint(6) DEFAULT NULL,
  PRIMARY KEY (`job_id`),
  KEY `source_id_idxfk` (`source_id`),
  KEY `facility_id_idxfk` (`facility_id`),
  KEY `job_type_id_idxfk` (`job_type_id`),
  KEY `template_id_idxfk` (`template_id`),
  CONSTRAINT `jp_job_ibfk_1` FOREIGN KEY (`source_id`) REFERENCES `jp_source` (`source_id`),
  CONSTRAINT `jp_job_ibfk_2` FOREIGN KEY (`facility_id`) REFERENCES `adm_facility` (`facility_id`),
  CONSTRAINT `jp_job_ibfk_3` FOREIGN KEY (`job_type_id`) REFERENCES `jp_job_type` (`job_type_id`),
  CONSTRAINT `jp_job_ibfk_4` FOREIGN KEY (`template_id`) REFERENCES `jp_template` (`template_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

I had copied and pasted the same in phpmyadmin to create the same table, then i got the following error
Error:
InnoDB

Supports transactions, row-level locking, and foreign keys

[ Variables | Buffer Pool | InnoDB Status ]

Can anyone please let me know how to edit the code in order to avoid errors and create a table in phpmyadmin sql editor

A: It seems that INNODB Engine is disabled on your server. Just remove any disable options for innodb in /etc/my.cnf and restart mysql.


text:
Q: Remove a specific string common in multiple lines in a CSV file using shell script I have a CSV file which contains 65000 lines (size approximately 28 MB). On each of the lines they have a path in the beginning in the format of: c:\abc\bcd\def\123\456.
Now let's say the path c:\abc\bcd\ is common in all the lines and the rest of the content is different. I have to remove the common part from all the lines. In this case, c:\abc\bcd\.
How can I remove this using a shell script?

A: Using sed and writing the output to a new file so it can be checked.
sed 's/c:\\abc\\bcd\\//' csv-file > new-file


text:
Q: Paypal payment destroys Session on "Return" This question has been asked before.  But, I am still unable to find a solution.
I have integrated Paypal Payment into my website.  I created and installed the "Payment Button"  (the HTML code), and it works perfectly.
The problem, however, is that : after being re-directed to Paypal to make the payment, the user's session on my website is destroyed. Meaning : after payment is successful (or canceled by the user, whichever).......the "Return URL" does not work, because the user has been logged out.
I did contact paypal, of course; and, as I expected, they were next to useless (exactly as many people here have already attested to).
As I said earlier, this question has been asked before, here :
Anybody ever used PayPal Website Payments Standard with SESSION variables?
The answer proposed by "Woppi" in that thread seemed ok. But, when I tried it, it did not work.  (of course, that thread is 3 years old).
I really don't know what else to do.
I should point out the following, however (this makes no difference, but I want to be as clear as possible) :
(a) On my website's "Log-Out Page", I have set all sessions to be destroyed :
     session_unset();

     unset($_SESSION['login']);
     unset($_SESSION['password']);

     session_destroy();

     session_write_close();

As far as I can see, there is nothing wrong with this code. It completely wipes out and destroys any and all sessions (which should be the case, shouldn't it?  Otherwise, what is the point of logging out? )
(b)  I do not have "Cookies" set anywhere  (which may be part of the problem, although I am not sure). However, I do have these in my HTML header :
    <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Expires" CONTENT="0">

(c)  In the old thread (given above), it requires the value : $session_id;
At the beginning of every PHP page in my website, I have the :
   **<?php session_start();**

This has worked so far for me; I did not assign any specific ID anywhere else.
UPDATE
I am now using cookies in my PHP to try to resolve this problem;
At the top of the PHP payment form, I have this :
  <?php session_start();

  if (!(isset($_SESSION['login'])) {

  header ("Location: /example/access_denied");

  exit() ;
  }

  $cookie_name = "user_paying";
  $cookie_value = $_SESSION['login'];
  $date_of_expiry = time() + 600 ;

  setcookie($cookie_name, $cookie_value, $date_of_expiry, '/', FALSE,TRUE);

(I set cookies to expire after 10 minutes);
Then, in my "Return-Form"  (where the user is re-directed after making payment in Paypal),  I have this at the top :
 <?php session_start();

 if (!isset($_COOKIE['user_paying'])) {
 setcookie($cookie_name, $cookie_value, $date_of_expiry, '/', FALSE,TRUE);
 }

 else {

 // etc, etc, etc..........code continues


text:
Q: Do something in background I have some framework of mine which is do something that takes time,  and when i am trying to call a method of it , it actually freeze for 0.5 sec the movement in the screen .
i was trying to call it in background with :
[self performSelectorInBackground:@selector(transmitNow:) withObject:nil];

-(void)transmitNow:(id)sender
{
     [instance sendWithData:data]; //takes time

}

but it still takes the same amount of time .
is there a way to start this in the background so it will not stop the main process ?
Thanks .

A: Yes. You can use and NSOperationQueue and NSOperation to do this. Consider the following code:
NSOperationQueue* queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:
^{
     [instance sendWithData:data];
}];

This will create an NSOperationQueue which is essentially a background thread. It will add an operation to that queue which will complete and then the thread will be automatically closed and cleaned up.
Read up on NSOperations and NSOperationQueue for more information.

A: I'd use GCD (Grand Central Dispatch):
dispatch_async(dispatch_get_global_queue(0, 0), ^{
    [instance sendWithData:data];
};

A: what you seem to have written should do what you want , I would put a breakpoint in make sure that is happening, also by calling this on a single threaded app, you will be switching to multi-threaded mode, which could account for the time you are seeing. calling again may be very fast.
doing things in the background can also be dangerous so be prepared to do some locking:
-(void)transmitNow:(id)sender
{
    @synchronized(data)
    {
         [instance sendWithData:data]; //takes time
    }
}

also know that if you main thread runs into contention on data, it may still hang... just an fyi.


text:
Q: Oracle + ASM + LVM + Pacemarker I need to create a cluster with RedHat7 (pacemarker) for a Oracle database. The DBA say that need to use Oracle ASM for manage disks but Cluster need use LVM. Can I use LVM and ASM ?

A: Event though I don't like to just quote text from the documentation as an "answer" I think it does the job in this case :)

"Although you can specify a logical volume as a device in an Oracle
  ASM disk group, Oracle does not recommend their use because it adds a
  layer of complexity that is unnecessary with Oracle ASM. In addition,
  Oracle RAC requires a cluster logical volume manager in case you
  decide to use a logical volume with Oracle ASM and Oracle RAC." http://docs.oracle.com/database/121/CWLIN/storage.htm#CFACJAGB

You have three choices:

*

*don't use LVM use ASM instead

*don't use ASM use LVM instead

*ignore Oracle's recommendation and use LVM + ASM.

If you don't plan on installing a RAC, I see the need of using ASM.


text:
Q: "Ubuntu One" authentication Failure in Windows 7 I just updated the Ubuntu One client on my Windows 7 machine today.  When I try to sign in, I receive the "authentication failed" error message, even though the same credentials work on the Ubuntu One website and my Ubuntu 11 machine at work.  Any suggestions?

A: There seems to be authentication bugs in the latest windows client for ubuntu one. Download earlier version from http://one.ubuntu.com/windows/ubuntuone-2.0.3-windows-installer.exe and install it.
It should work and check for the change-logs in the future releases and updates for this bug to be fixed.

A: There was a problem validating the SSL certificate in some cases. Could you try the latest version (4.0.0) and see if that fixes it for you?


text:
Q: Why Toast doesn't work with MaterialComponent theme? When i use default AppCompattheme my toast works, but when i use Material theme, there error appears.
Binary XML file line #27: Error inflating class TextView
And when i change Toast  to Snackbar error disappears!!


text: Q: "The required options you selected are not available." in cart in Magento-2.1? Bundle option id is change every time,when i will any change like add some option or remove some option.Suppose I have one bundle product in cart before changes.After bundle product changes, Carts is showing error "The required options you selected are not available." in Magento-2.1. How to solve this error,Please help me this is major issue.


text:
Q: CSS Values in a D3 Transition box shadow I'm wanting to do a d3 transition based on style based in the css. However I am not able to do it for the box-shadow. Have I made a mistake or is it not supported?
var first = d3.select('.first'),
second = d3.select('body').append('div').attr('class', 'second').style('display', 'none'),
color = second.style('box-shadow');
first.transition().duration(3000).style('box-shadow', color);

.first {
  width: 100px;
  height: 100px;
  box-shadow: 0px 0px 4px 1px gray inset;
}
.second {
  width: 100px;
  height: 100px;
  box-shadow: 0px 0px 4px 1px blue inset;
}

Here is the example in fiddle:
http://jsfiddle.net/zasDK/4/
Here is a working example that works with background-color (I based my code on this one):
http://jsfiddle.net/linssen/zasDK/

A: The problem is that you are getting the canonical form of the box-shadow style when you are retrieving it using D3. This is "rgb(0, 0, 255) 0px 0px 4px 1px inset" in this case, and quite different from how you specified it in your CSS. Now D3 doesn't know how to interpolate between the strings
0px 0px 4px 1px gray inset

and
rgb(0, 0, 255) 0px 0px 4px 1px inset

and nothing happens. It works if you explicitly specify the new style in the same format as the first, see this fiddle.
However, this doesn't really give you the transition you want in this case. One approach to fixing this is to use a different way of declaring the style (see paulitto's answer), but this may not be possible depending on what other styles you're using. The second way of fixing this is to use a custom style tween. In particular, you only need to interpolate the colours here as the rest stays constant. In code, this looks like this.
first.transition().duration(3000)
  .styleTween("box-shadow", function() {
    var i = d3.interpolate("gray", "blue");
    return function(t) {
        return "0px 0px 4px 1px " + i(t) + " inset";
    };
  });

Complete demo here.

A: If you only want to make transition for shadow color, you can use the fact that it inherits color css property.
Change your css to this:
.first {
    width: 100px;
    height: 100px;
    box-shadow: 0px 0px 4px 1px inset;
    color: gray;
}
.second {
    width: 100px;
    height: 100px;
    box-shadow: 0px 0px 4px 1px inset;
    color: blue;
}

And animate color instead of box-shadow:
first.transition().duration(3000).style('color', color);

See updated fiddle


text:
Q: How to read string containingg asterisk from a file in shell script? I have a file containing a number of lines as follows
source destination pattern

the pattern may have *.* also
When I read this pattern into a variable PATTERN using
cat $FILE_NAME|while read item
do
    arr=($item)
    PATTERN="${arr[2]}"
    echo "$PATTERN"
    done

then the output is some file in the working directory. How can I store "*.*" in PATTERN ?

A: By doing it the right way in the first place.
while read -a arr
do
    PATTERN="${arr[2]}"
    echo "$PATTERN"
done < "$FILE_NAME"


text:
Q: Extract elliptical region and crop it with with manually in Matlab I have many face images, I want to extract an elliptical region from the images by manually and crop and save it automatically(like imcrop but not a rectangle).
Could you help me about this?
Thanks for your help

A: You can use the imellipse function.

A: %This is what you would do after creating the mask to get the coordinates.

structBoundaries = bwboundaries(binaryImage);
xy=structBoundaries{1}; % Get n by 2 array of x,y coordinates.
x = xy(:, 2); % Columns.
y = xy(:, 1); % Rows.

However a better way would be to use the code below. Essentially, it asks the user to select an image and then the user crops the image manually and then it saves to the location of where the original image is.
[FileName,PathName] = uigetfile({'*.jpg;*.tif;*.png;*.gif','All Image Files'},'Please Select an Image');
image = imread([PathName FileName]);
imshow(image) %needed to use imellipse
user_defined_ellipse = imellipse(gca, []); % creates user defined ellipse object.
wait(user_defined_ellipse);% You need to click twice to continue.
MASK = double(user_defined_ellipse.createMask());
new_image_name = [PathName 'Cropped_Image_' FileName];
new_image_name = new_image_name(1:strfind(new_image_name,'.')-1); %removing the .jpg, .tiff, etc
new_image_name = [new_image_name '.png']; % making the image .png so it can be transparent
imwrite(image, new_image_name,'png','Alpha',MASK);
msg = msgbox(['The image was written to ' new_image_name],'New Image Path');
waitfor(msg);


text:
Q: made them sit up straight vs. made them sit upright Do "sit up straight" and "sit upright" share the same meaning? Are they interchangeable?

On 8 December, during a regular Tuesday meeting about the spread of the pandemic coronavirus in the United Kingdom, scientists and public health experts saw a diagram that made them sit up straight. Kent, in southeastern England, was experiencing a surge in cases, and a phylogenetic tree showing viral sequences from the county looked very strange, says Nick Loman, a microbial genomicist at the University of Birmingham.

Source: Science

A: Sit up straight, as well as describing a person's posture, is an idiom meaning suddenly start to pay particular attention. Those experts were in a routine meeting when they saw the first evidence of the new variant of Covid-19.
We only use sit upright in its literal sense.


text:
Q: Is ionic will slow down the process with multiple pages I've started with ionic and angular.
In our app we are just showing the data we're getting from server. But there will be 20+ pages. And I've checked Ionic docs, It's mentioned that Ionic will maintain the history and state. So is that will slow down the performance of app if multiple pages are loaded in background ?
I faced a lot of issues in one of my app(which was completely JS and JQuery based), because we were running 3 threads in background, it was slowing down the UI, UI was too much jerky in that case.
Just want to take care about this, your suggestion is worth a lot for me.
Thanks


text:
Q: React API not showing the data I am not able to retrieve content from API every time I reload my page it shows error, please see the attached image, I wanted to find the weather details using Weather API and right now I am using static latitude and longitude.
import React, { useState, useEffect } from "react";
import axios from "axios";
import { FaRegSun } from "react-icons/fa";
import "./stylesheets/stylesheets.css";

function WeatherApp1() {
  const [weatherData2, setWeatherData2] = useState({});

  const API_endpoint2 = `https://api.openweathermap.org/data/2.5/onecall?`;
  const API_key = `2a63c27d8ba0b0d14c9e5d59f39ee1ba`;

  useEffect(() => {
    async function getSecondObject() {
      const response = await axios.get(
        `${API_endpoint2}lat=28.4360704&lon=77.021184&units=metric&appid=${API_key}`
      );
      setWeatherData2(response.data);
    }
    getSecondObject();
  }, []);

  return (

          <FaRegSun /> Weather

      {weatherData2.current.temp}

  );
}

export default WeatherApp1;

https://i.stack.imgur.com/oqr7i.jpg

A: The problem with your code is that you're trying to render {weatherData2.current.temp} before the data is returned from the weather API and that's why your weatherData2 will be undefined while rendering.
You can add a loading state for checking if the data is rendering or already rendered.
You can try below code:
import React, { useState, useEffect } from "react";
import axios from "axios";
import { FaRegSun } from "react-icons/fa";
import "./stylesheets/stylesheets.css";

function WeatherApp1() {
  const [loading, setLoading] = useState(true) // Loading state
  const [weatherData2, setWeatherData2] = useState({});

  const API_endpoint2 = `https://api.openweathermap.org/data/2.5/onecall?`;
  const API_key = `2a63c27d8ba0b0d14c9e5d59f39ee1ba`;

  useEffect(() => {
    async function getSecondObject() {
      const response = await axios.get(
        `${API_endpoint2}lat=28.4360704&lon=77.021184&units=metric&appid=${API_key}`
      );
      setWeatherData2(response.data);
      setLoading(false) // Setting the loading state to false after data is set.
    }
    getSecondObject();
  }, []);

  return (

          <FaRegSun /> Weather

       {/* Checking for loading state before rendering the data */}
      {loading ? (

Loading...

      ) : (
         weatherData2.current.temp
      )}

  );
}

export default WeatherApp1;


text:
Q: Dynamic content of resize image in sharp aws lambda I am using sharp to resize images on AWS Lambda.
It works fine for testing but the issue is that how to give dynamic content type according to the content type of image.
My code is
then(buffer => S3.putObject({
    Body: buffer,
    Bucket: dstBucket,
    ContentType: 'image/jpeg',
    Key: dstKey,
  }).promise()
)

I want this contentType is according to buffer content Type.


text:
Q: How to call C++ functions with different signatures through function pointer I have a C++ application where main() instantiates an object, MyApp, and then passes the object to a ReadConfig function.
ReadConfig opens a text based file, parses it, and calls the appropriate MyApp methods to configure it.
class MyApp
{
private:

public:
  void SetRate(uint16_t);
  void EnableLogging(bool);
  void SetAddress(uint32_t);
};

I'm trying to make it easy to maintain ReadConfig such that as new public methods are added to MyApp, it can be as simple as updating a table.  I have come up with the following solution but I don't like it.  It's hard to maintain due to having to make sure I put 0s in the right place.
Below is a example of what I've been able to work out.  Any advice to make this better would be appreciated.  Note I work in embedded so the C++ compilers we use don't support C++14 & there is no boost.  And I would like to avoid using any STL libraries so as to understand the mechanics of doing this myself.
Here is what I have:
enum ARGTYPE {TBOOL, TUINT16, TUINT32};

template<typename TOBJ, typename TARG>
struct TSetting
{
  void (TOBJ::*FSet)(TARG);
};

template<typename obj>
struct SETTINGFN
{
  const char                       *setting_name;
  ARGTYPE                          Targ;
  TSetting<obj,bool>               HBool;
  TSetting<obj,uint16_t>           HUint16;
  TSetting<obj,uint32_t>           HUint32;
};

SETTINGFN<MyApp> MyAppSettings[] =
{
  "logging"    ,TBOOL,       &MyApp::EnableLogging, 0,0,0
  ,"maxrate"   ,TUINT16,     0,0,0,&MyApp::SetRate
  ,"address"   ,TUINT32,     0, &MyApp::SetAddress, 0,0

};
unsigned int MyAppSettings_Count = sizeof(MyAppSettings) / sizeof(SETTINGFN<MyApp>);

Then as I read the config file and parse it, I call a function to handle calling the actual MyApp functions through the function pointers.  That function is as follows:
bool AppSetting(MyApp &E, TObjnode &node)
{
  bool rval = false;

  for(unsigned int i=0; i<MyAppSettings_Count && !rval; i++)
  {
    if(node.GetName() == MyAppSettings[i].setting_name)
    {
      rval = true;

      switch(MyAppSettings[i].Targ)
      {
        case TBOOL:
          (E.*MyAppSettings[i].HBool.FSet)(node.GetValue().AsBool());
        break;

        case TUINT16:
          (E.*MyAppSettings[i].HUint16.FSet)(node.GetValue().Value());
        break;

        case TUINT32:
          (E.*MyAppSettings[i].HUint32.FSet)(node.GetValue().Value());
        break;
      }
    }
  }

  return(rval);
}

A: The thorn in your design is the different parameter types.
If the parameters are abstracted into a structure, then the functions can be simplified to one fixed signature.
By using a base structure, the signatures and be more generic:
struct Arguments_Base
{
};

void SetRate(Arguments_Base& ab);
void EnableLogging(Arguments_Base& ab);
void SetAddress(Arguments_Base& ab);

By having uniform signatures, function pointers or function objects can be used in tables or maps, making searching easier.  The search engines should be able to be generic and depend on the size of the data so that only the data (e.g. table) needs to be changed, not the search engine.
Each type of set of arguments should be derived from the Arguments_Base class.  The function can then dynamic_cast the base class reference.
See also: Factory Design Pattern, Visitor Design Pattern, Double Dispatch


text:
Q: WebApi access Exchange mailbox folder Calendar,Notes,Tasks I need create a procedure for rename some folder on user mailbox in Office365.
I have used Microsft Graph API but I'm not able to find folder who are not "mail folder". In Exchange you can create other type of folder (Contact,Tasks,Notes).
There is a API who can manage this kind of folders?
Thanks

A: There are multiple folder types supported:

*

*Mail Folder

*Contact Folder

*Tasks Folder (beta)

*Calendar Group
Outlook Notes are not supported by Microsoft Graph.


text:
Q: Use class from specific other assembly if that assembly is loaded, performantly and without any boilerplate code I will describe the situation in abstract terms, as the actual subject of the code is irrelevant for the time being. This question is merely about the architecture/code organisation in the project.

I am creating a set of reusable C# libraries.
Assembly A offers a set of related features.
A few of these features require an implementation of ISomething.
The implementation of ISomething to use is determined in a static configuration class provided by A, Config.Something.
Assembly B contains an implementation of ISomething, namely DefaultSomething.
I am looking for a way to

*

*let users use assemblies A and B by simply referencing them and accessing types from A. In this situation, Config.Something should automatically be set to/assumed to be DefaultSomething.

*let users use assembly A and supply their own implementation of ISomething. In this situation, assembly B should not be required and users should be able to assign a custom object to Config.Something.

*let users use only those features from A that do not require ISomethings, so neither B nor an assignment to Config.Something are required.

While cases (2) and (3) are trivial, I am not sure how to best design the library to support case (1).
I have examined various ways to solve this, but each of them has some drawbacks:

*

*Users could be asked to perform the assignment Config.Something = new DefaultSomething() themselves in case (1). However, I do not want to require this sort of boilerplate code. Case (1) should be really "plug-and-play", or rather, reference-assemblies and write custom code using A.

*In case (1), the code in A could search for class DefaultSomething by means of reflection the first time an ISomething is required. However, especially when many assemblies are loaded, this seems quite wasteful and slow. I might be able to identify B relatively quickly by marking it with a custom attribute declared in A that is not publicly visible, but giving B access to A's internals. This sounds somewhat hacky, though.

*B registers itself with A as soon as B is loaded. This would be my preferred solution, but I don't think there is any way to automatically run any code from an assembly once that assembly has been loaded.

Is there any good way to do this?

A: Without specific examples there will be a lot of ways to achieve that.
Generally speaking, looks like you need a IoC Container (like Unity/Ninject if you are using .NET) and/or a plugin system (handmade, or MEF if you are using .NET).


text:
Q: Flutter Keyboard with Math Operators How do I get a keyboard with Mathematical operators in Flutter? Something like this screenshot from Venmo? I'm not seeing a keyboardType or dart package that seems to do the trick.
Thanks!

A: Did you have a look at the math_keyboard package?
It seems to be doing exactly what you want.


text:
Q: How to restore a Wordpress into which another web app was installed So I created a database in cPanel to install SMF into for my WordPress website, but I accidentally made my home URL the place to host the forums.  It overwrote my entire website.  I can't access any of the pages anymore without it redirecting me to my SMF forum.  I deleted the database that the forum was connected to and it's just giving me an error now if I try to go to my website.  Is there anyone that can point me in the right direction here?

A: I guess you'd have to try and restore the files on the top level, most importantly index.php and .htaccess.
When that is done, you'll have to hope that SMF didn't overwrite any important Wordpress directories. If it didn't, your install should work again.
index.php and any other files in the top directory you should be able to copy from a raw Wordpress install.
The only exception is the .htaccess file which contains the routes for pretty URLs (if you use those - if you don't, skip this paragraph). This file has been generated specially for your install. To re-create it, you should be able to access your wp-admin directory already, and update the permalink structure.


text:
Q: Makefile for compiling Markdown files to a single PDF I am trying to use a Makefile for compiling a PDF when any of a number of Markdown files change:
# Compile report

source := draft
output := dist
sources := $(wildcard $(source)/*.md)
objects := $(patsubst %.md,%.pdf,$(subst$(source),$(output),$(sources)))
all: $(objects)

report-print.md: $(source)/%.md
    cat draft/*.md | pandoc \
        --variable geometry:a4paper \
        --number-sections \
        --toc \
        --f markdown \
        -s \
        -o dist/report-print.pdf \

.PHONY : clean

clean:
    rm -f $(output)/*.pdf

I get an error:
make: *** No rule to make target `dist/01-title.pdf', needed by `all'.  Stop.

The file draft/01-title.md is one of of the source files.

A: You don't have a rule for creating one .pdf file from one .md file.  Which is fine, because that's not what you want to do.  You want to create a single pdf file from all the .md files (as I understand it).  So, ditch all the objects stuff; you don't need to create all those individual pdf files.
There are a number of other minor problems: you aren't creating the same filename as your target (report-print.md vs. $(output)/report-print.pdf), you should use automatic variables, etc.)
Your makefile will simply be:
source := draft
output := dist
sources := $(wildcard $(source)/*.md)

all: $(output)/report-print.pdf

$(output)/report-print.pdf: $(sources)
        cat $^ | pandoc \
            --variable geometry:a4paper \
            --number-sections \
            --toc \
            --f markdown \
            -s \
            -o $@

.PHONY : clean

clean:
        rm -f $(output)/*.pdf


text:
Q: WatchKit Long Look: how to start content from underneath the Sash? I found following text in the Apple documentation about WatchKit's Long Look (the detail view of a push notification):

The content area ... For custom interfaces, you can configure this area to start underneath the sash or just below it.

How to start the content from underneath the sash? I'd like to partially overlap an image with the sash, but couldn't find any options for that (could only layout all my content below the sash).

A: On the watchkit forums over at developer.apple.com there was a discussion about this topic. It's removed from beta 5 by design and that's all we know right now.
edit: I found out how to get this to work!
Select the "Static Notification Interface Controller"
Change the color field

A: This is good question and...I can't answer it directly.
The thing is: if you download Xcode Beta 4, content will start from underneath the Sash.
However in Xcode Beta 5 it starts from below lower edge of sash. Don't know whether it's a bug or feature.


text:
Q: How to standardise different date formats in pandas? I have a dataset in csv format which contains dates in a column. I have imported this dataset into python pandas, and this date column is shown as an object. I need to convert this column to date time but i have a problem. This date column has date format in two formats
1. 11/7/2013  11:51
2. 13-07-2013 08:33:16
I need to convert one format to another one in order to have a standard date format in my python to do analysis. How can i do this?
There are many rows of date in both these formats, so when i try to convert second format to first format using the below code

print(df['date'].apply(lambda x: pd.to_datetime(x, format='%d/%m/%Y
  %H:%M')))

i get the below error

ValueError: time data '13-07-2013 08:33:16' does not match format
  '%d/%m/%Y %H:%M' (match)

so what would be the best method to standardise this column in one format?

A: Try removing the format parameter and setting infer_datetime_format=Truein the arguments you pass to pd.to_datetime

A: You can try the following
import pandas as pd
import numpy as np

n=1000
ch = ['13-07-2013 08:33:16', '13/07/2013 08:33:16']
df = pd.DataFrame({"date": np.random.choice(ch,n)})

df["date"] = df["date"].str.replace("/","-").astype("M8[us]")

Update
I just realize that the format I'm using is not the same you would like. I strongly suggest you to use a standard format as YYYY-MM-DD and datetime as type instead of string. There are a lot of post that explains why this is more efficient on RAM and then faster.
A small comparative for a df with just 1000 rows
%%timeit
out = df["date"].str.replace("/","-").astype("M8[us]")

146 ms ± 5.62 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
out = df["date"].apply(lambda x: pd.to_datetime(x)\
                                   .strftime('%d/%m/%Y %H:%M'))

396 ms ± 22.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
out = df['date'].apply(lambda x: pd.to_datetime(x,
                       format='%d/%m/%Y %H:%M',
                       infer_datetime_format= True))

425 ms ± 4.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: its better to use strftime():
df = pd.DataFrame({'Date': ['11/7/2013 11:51','13-07-2013 08:33:16']})
df['Clean_Date'] = df.Date.apply(lambda x: pd.to_datetime(x).strftime('%d/%m/%Y %H:%M'))
print(df)

output:
                  Date        Clean_Date
0      11/7/2013 11:51  07/11/2013 11:51
1  13-07-2013 08:33:16  13/07/2013 08:33

A: In Pandas v1 to_datetime function is very robust and can handle most date formats. With your example dates it is as easy as calling to_datetime on your series.
d = ['11/7/2013 11:51', '13-07-2013 08:33:16']
df = pd.DataFrame({'dates': d})
df = pd.to_datetime(df['dates'])
df

output
0   2013-11-07 11:51:00
1   2013-07-13 08:33:16
Name: dates, dtype: datetime64[ns]

Just how robust is to_datetime?
lets tests it using a dataset of 25 different date styles from here.
http = r'https://www.ibm.com/docs/en/cmofz/10.1.0?topic=SSQHWE_10.1.0/com.ibm.ondemand.mp.doc/arsa0257.htm'
table = pd.read_html(http)
df = table[0]
df

# test which datestyles pandas can convert
df['Example_clean'] = pd.to_datetime(df['Example'])
print(df.dtypes)
df
# yes it converted all 25 different date formats!!
# Note - when using a time it automatically uses todays date.

output


text:
Q: Wordpress PHP proxy/helper pages for Twitter API Ok I am currently doing some work on my personal blog.
On the home page I am displaying my latest tweet using a bit of jQuery code.
$.getJSON('https://api.twitter.com/1/statuses/user_timeline/killfall.json?count=1&callback=?', function(data) {
    tweet = data[0]['text'];
    tweet = tweet.replace(/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i, "$1");
    $('#tweet-text').html("“" + tweet + "“");
});

This just gets my latest tweet from twitter, converts any URLs to anchor tags and puts that in a div with an id of tweet-text.
However I feel I should probably be using oauth and the newer version of the twitter api due to the fact that I keep getting an error message saying
"error":"Rate limit exceeded. Clients may not make more than 150 requests per hour."

and I believe using oath will solve this problem.
The thing I want to know is how it would be best to implement this. I want to continue to use ajax in jQuery to load the tweet so that it loads it after the page has finished loading.
My instinct makes me think I should have some JavaScript like
var jqxhr = $.ajax( "<?php bloginfo('template_directory');?>/ajax/get_tweet.php" )
.done(function() {
    tweet = tweet.replace(/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i, "$1");
    $('#tweet-text').html("“" + tweet + "“");
 })

And then create a php file which would act as a proxy/helper in the theme folder in a dir called ajax called get_tweet.php which would do the oauth stuff and just echo the latest tweet which would be used by the JavaScript.
But I'm just wondering if putting random php files inside a wordpress theme like this is good practice or if there is a better way of doing it?


text:
Q: What is the Opensearch equivalent of the Elasticsearch config value index.mapping.total_fields.limit I have an error in my Opensearch cluster: "Limit of total fields [1000] has been exceeded". I can see that this problem can be fixed in Elasticsearch by setting index.mapping.total_fields.limit to a higher value.
But looking in my Opensearch cluster settings, this setting doesn't seem to be there.  I tried modifying it using Terraform but I got this error:
 Error: ValidationException: Unrecognized advanced option 'index.mapping.total_fields.limit' passed in advancedOptions.
│
│   with module.opensearch.aws_elasticsearch_domain.aws_opensearch,
│   on ../modules/opensearch/main.tf line 27, in resource "aws_elasticsearch_domain" "aws_opensearch":
│   27: resource "aws_elasticsearch_domain" "aws_opensearch" {

I can't find any mention of how to adjust the mapping total fields limit in the Opensearch documentation for our cluster version 1.1
Does anyone know the name of the equivalent setting in Opensearch?

A: This is an index-level setting, you can retrieve it with
GET your-index/_settings?include_defaults

You can change it dynamically with
PUT your-index/_settings
{
  "index.mapping.total_fields.limit": 2000
}

Note that when increasing this setting, it is recommended to also increase indices.query.bool.max_clause_count, but since that's a static setting, it's unlikely you can change it in AWS: