text:
Q: HTML + CSS table layout Maybe I'm going about this all wrong but I can't seem to figure out a simple layout.  I basically want a header than spans 100% width and have a fixed height (say 120px).  I then need a left menu and the content on the right.  If the viewport changes, I need to show scrollbars if the content is greater than the viewport (overflow: auto).  BUT, I can't seem to make it work properly.  Here's what I have so far:

    <title>Client Layout Test</title>

CLIENT NAME AND LOGO GO HERE!

                        List of links goes here

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse condimentum egestas nulla nec accumsan. Suspendisse pretium luctus rhoncus. Suspendisse euismod, magna non tempor lobortis, sapien velit ornare est, a venenatis enim erat a lectus. Nunc placerat, lorem ac viverra aliquet, nisl nunc varius sem, nec commodo dui mauris interdum augue. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras vulputate nunc non lorem mattis luctus. Sed sit amet lorem venenatis ipsum blandit commodo. Mauris tempor dolor a nisl tristique volutpat. Aliquam tincidunt rhoncus diam vitae faucibus. Sed consequat diam in eros laoreet placerat.

Pellentesque consectetur tincidunt tortor, a laoreet massa interdum vitae. Nam faucibus ante sit amet lacus pulvinar eleifend. Sed iaculis tempor nunc ut tincidunt. Phasellus id metus ac purus fringilla pellentesque pulvinar nec arcu. In augue lacus, imperdiet et egestas vel, laoreet eget lorem. Donec ante tellus, feugiat eu feugiat sed, consequat sed felis. Duis porta est sit amet erat lacinia vehicula. Nullam congue luctus sapien, ut suscipit augue varius a. In consectetur dignissim urna. Donec adipiscing ornare magna eget laoreet. Fusce purus mauris, vestibulum id feugiat ac, pretium at libero. Nam placerat, ante ornare gravida cursus, magna risus eleifend dolor, ut auctor velit purus at ligula. Nullam ultrices, orci fermentum semper euismod, velit metus condimentum lacus, consequat interdum dolor orci ut elit.

Aliquam quis nibh ac ipsum dignissim sodales ac id arcu. Ut rutrum dolor at mauris ullamcorper dignissim. Vivamus sagittis iaculis varius. Nullam pharetra enim id lectus placerat venenatis. Ut gravida nisl magna. Praesent pretium viverra convallis. Nullam molestie, est vitae luctus rhoncus, ante mi porttitor dolor, id fermentum sem eros et dui. Quisque imperdiet, justo nec aliquet dictum, lorem felis pulvinar augue, at facilisis magna metus a elit. Fusce molestie nunc nec dui blandit nec cursus neque molestie. Sed tempus metus et neque malesuada ut lacinia tortor suscipit. Sed tristique sagittis elit, tempor tincidunt augue tempus at. Vestibulum convallis volutpat euismod.

Integer mattis vulputate viverra. Cras ultrices, lectus vitae mollis pharetra, dui odio porttitor quam, vel iaculis arcu felis vel arcu. Nam posuere viverra erat, nec molestie nunc egestas a. Proin pharetra, velit quis pretium ullamcorper, arcu dui condimentum sem, eget vulputate urna turpis vitae lorem. Suspendisse vitae felis sit amet odio dapibus vulputate. Nam hendrerit tempor neque, ac dapibus turpis ullamcorper eget. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed ipsum justo, venenatis in dignissim sit amet, consectetur gravida elit. Praesent tincidunt, orci vel elementum condimentum, nisl purus auctor orci, in ullamcorper nulla nisl et mi. Suspendisse volutpat urna vel nunc dapibus venenatis consequat nibh blandit. Cras id ipsum orci. Pellentesque eget odio dui. Fusce porta erat quis eros ornare varius. In viverra dui nec est rhoncus sed tincidunt augue imperdiet. Etiam a lectus et dui mollis fringilla.

Sed odio sapien, viverra in egestas eu, tempor consequat erat. Vestibulum laoreet felis eu ante dapibus porttitor malesuada quam varius. Morbi egestas quam nec metus ultrices ultricies. Sed lacus libero, mattis ut feugiat at, iaculis a orci. Fusce ullamcorper accumsan dui. Aenean sit amet condimentum velit. Suspendisse turpis magna, ornare in sodales vitae, lacinia id elit. Sed non nulla ac augue egestas lacinia et a arcu. Aenean vel dolor lectus, eu imperdiet sem. Integer vel tellus sed dolor mattis condimentum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Phasellus eget massa massa, imperdiet volutpat velit. Duis a massa sit amet ligula scelerisque venenatis semper at ipsum. Aenean varius nisi a diam pretium ac facilisis metus aliquet. Ut tempus ante ac leo cursus in convallis nibh malesuada. Praesent sit amet eros neque, luctus fringilla nisi. Aliquam erat volutpat. Nam est erat, volutpat eget vulputate eget, gravida ut lorem. Nam ultricies nibh nec turpis vulputate lacinia eget vel eros. Nullam nulla tellus, porttitor id tempor non, rhoncus vitae neque.

Here's what it looks like:

Here's the issues and what I need it to do:

A: Here is a jsbin to help you get started:
http://jsbin.com/exevi3/edit
Hope this helps. Notice that the example is using css for layout instead of tables. That is the recommended best practice these days.
Bob
Here is the jQuery:
$(document).ready(function(){
  setHeight();
  $(window).resize(function(){
    setHeight();
  });

  function setHeight(){
    var headHeight = $("#header").height();
    var docHeight = $(window).height();
    var h = docHeight - headHeight - 50;
    $("#menu").css('height', h + 'px');
    $("#content").css('height', h + 'px');
  }
});

The '50' in there is because there is some additional padding not being accounted for. Could be that I should be using innerHeight().
Here is the HTML:

    header

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

item

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc rutrum aliquam diam, et facilisis lectus auctor vel. Praesent sit amet ante sem, id commodo leo. Praesent eget nisl leo. Quisque vel lectus metus. Morbi pellentesque scelerisque ipsum, eget fermentum sapien molestie et. Vestibulum quis elementum augue. Donec consectetur elit id ligula imperdiet a euismod mi pharetra. Nulla nec sapien et lectus porta sodales. Aliquam sed egestas justo. Integer adipiscing, felis non vehicula commodo, leo tellus aliquam nulla, et cursus nibh felis ac risus. Duis sit amet tempor lectus.

Ut mauris tellus, auctor ut mollis vitae, malesuada at nunc. Aenean condimentum ullamcorper viverra. Etiam elementum erat eget nulla bibendum a faucibus purus feugiat. Nam enim eros, placerat vitae volutpat tincidunt, tristique ac lectus. Proin elit risus, eleifend non varius eget, pretium non lectus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla blandit lacus blandit nisl porttitor eleifend. Sed adipiscing, leo nec pellentesque tempus, tellus velit pulvinar turpis, euismod pulvinar est odio et elit. Etiam quis turpis a tortor condimentum convallis eu nec velit. Nullam volutpat luctus nisi, in sollicitudin lectus adipiscing vitae. Pellentesque eu neque ut nisl iaculis lacinia nec non odio. Ut id nibh nec leo vulputate malesuada at sit amet risus. Mauris elementum dolor eget ligula pharetra vestibulum. In eu enim eu dui interdum vestibulum.

Ut quis libero et neque lobortis tempus. Quisque adipiscing eleifend lacus, iaculis adipiscing nibh porttitor ut. Sed dapibus nisl quis mauris sagittis blandit. Donec a tellus non ipsum mollis pretium. Morbi non lectus ut purus porttitor auctor. Praesent vulputate dictum augue nec elementum. Nulla facilisi. Duis auctor, metus molestie egestas pellentesque, sem nulla fringilla risus, a ultrices nunc sem ut eros. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras id neque volutpat nisl sollicitudin vestibulum auctor quis ligula.

Sed eget bibendum nisl. Ut nec odio massa, vitae posuere sem. Pellentesque vel urna sit amet sem gravida dignissim id vitae magna. Mauris aliquam, sapien pharetra malesuada bibendum, nisi metus auctor velit, eu egestas felis metus nec tellus. Morbi elementum pellentesque leo, eget facilisis nunc dictum sit amet. Integer cursus venenatis velit, a laoreet mi aliquet ut. Morbi nisi erat, tristique a porta vitae, hendrerit vel neque. Ut ipsum turpis, lobortis quis congue a, sagittis ut nulla. Donec massa sapien, consectetur facilisis lobortis in, aliquam at justo. Duis feugiat lacus sed sapien condimentum sollicitudin laoreet arcu semper. Phasellus sit amet odio at enim tincidunt congue. Ut ac ante eget eros facilisis faucibus non at mauris.

Vivamus ultrices dui eu nisi tempus semper. Suspendisse consectetur orci non lectus vestibulum dictum. Sed sodales diam vel magna scelerisque quis lobortis ipsum condimentum. Etiam sem orci, bibendum eget sagittis et, ullamcorper at nibh. In sed dignissim dolor. Aliquam erat volutpat. Curabitur vel euismod augue. Integer pulvinar ultrices velit, iaculis tincidunt est scelerisque sed. Integer non vehicula est. Cras pretium viverra augue, in accumsan ante dictum vehicula. Nulla facilisi. In imperdiet pretium tortor, eget vehicula tellus porttitor vel. Praesent erat erat, commodo ac euismod non, tempor sed sem. Fusce non elit nec velit consequat cursus. Phasellus placerat luctus erat, vitae porta sem pulvinar a. Mauris hendrerit neque vitae elit commodo convallis. In ac risus elit, non aliquam tellus.

And finally the CSS:
  #header{
    height: 120px;
    background-color: #000;
    color: #fff;
  }
  #menu{
    width: 300px;
    height: 400px;
    overflow-y: scroll;
    float: left;
    background-color: #ffdddd;
  }
  #content{
    height: 400px;
    overflow-y: scroll;
  }

Sorry those links don't work for you. Not certain why. Any way you should be able to plop this into a test.html page and see the solution.

A: First of all, don't use tables for this kind of things. Just use divs or proper HTML5.
Secondly, try setting a height on the elements that need a scrollbar. And add this " overflow-y: scroll; "
--> http://www.w3schools.com/Css/pr_pos_overflow.asp

A: You need to set the height of the menu-container to a concrete value (as in px NOT %) to allow it to scroll using: overflow-y: scroll;
Otherwise it doesn't know when to add the scrollbar.
See the simple example @ jsFiddle: http://jsfiddle.net/BfWXM/


text:
Q: toolbar blinks when switch between bottom nav fragments 【update】
Actually it's easy to reproduce the issue by just disabling the default ActionBar and adding Toolbar per fragment. Then you can see the toolbar blinks when switching bottom destinations.

Please check out the tiny demo at https://github.com/025nju/BottomNav
【original post】
I'm new on Android and my demo project is a BottomNav single activity project. I checked many posts and looks many people suffered from handling the toolbar in this senario, all fragments need to have its own toolbar.
The toolbar backgroud color blinks when switching between bottom tabs. Please see the gif and ignore the last blank frame.

How to eliminate the blink?
btw, no such issue when I was using the default ActionBar, which is not recommanded by official.
I tested on Nexus 6 api26 AVD and a real handset android version 9. Same issue. Below is related code for your referrence. Thanks a lot.
FragmentMoney.xml:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.money.MoneyFragment">

    <include android:id="@+id/fragment_base" layout="@layout/fragment_base"/>

    <TextView
        android:id="@+id/text_money"
        ... />
</androidx.constraintlayout.widget.ConstraintLayout>

fragment_base.xml which is for the toolbar defination:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/mToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_constraintTop_toTopOf="parent">
    </com.google.android.material.appbar.MaterialToolbar>

</com.google.android.material.appbar.AppBarLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

MoneyFragment.java:
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = fragmentMoneyBinding.getRoot();
    ...
    Toolbar mToolbar = (Toolbar) root.findViewById(R.id.mToolbar);
    mToolbar.setTitle(R.string.title_money);
    ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
    return root;
    }
}

activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toTopOf="@+id/nav_view"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/mobile_navigation" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/nav_view"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="0dp"
    android:layout_marginEnd="0dp"
    android:background="?android:attr/windowBackground"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toBottomOf="@id/nav_host_fragment"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:menu="@menu/bottom_nav_menu" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/floatingActionButton"
    ... />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_note, R.id.navigation_money, R.id.navigation_time)
            .build();
    navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupWithNavController(navView, navController);
}
...
}

A: You have to disable (replace) animation between fragments.
Create empty animation:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <!--Empty to disable animation-->
</set>

And put it into following files:
res/animator/nav_default_enter_anim.xml
res/animator/nav_default_exit_anim.xml
res/animator/nav_default_pop_enter_anim.xml
res/animator/nav_default_pop_exit_anim.xml

redpajama_set_name: RedPajamaStackExchange


text:
Q: General steps to create watershed boundary in ArcGIS Spatial Analyst? I am an ArcGIS beginner.
I have a CD of GIS files of a city and intend to work on watershed management.
There are different file names in different formats on CD. Like .shp, .shx, .dbf, .sbx. and I have no idea which one to choose to start working on.
As there is a file named contour line (in all mentioned formats) I would guess I need to start with that one. I am not sure, though. I also found out that I should use Spatial Analyst Extension but in which step I do not know.
What are the main steps, and which file to start with to end up with a 3D file of watershed and its boundaries?

A: Here are the general steps involved in creating a watershed boundary.

*

*You need to work with a raster DEM, not vector contours. This means that you have two options; you can either try to interpolate your contours or you can look for an existing raster DEM of the study area. Most of the interpolation methods contained within ArcGIS's interpolation toolbox are really intended to work with points rather than contour lines. You're right that the Topo to Raster tool is one interpolation routine that was specifically designed to work with contour lines and stream lines to create a hydrologically corrected DEM. If this is the route you decide to go, Topo to Raster is probably your best bet. However, depending on the necessary resolution (scale) and extent of the study area, you might be able to find an already existing DEM that would be suitable for application and therefore skip the interpolation step entirely. One common DEM data source that people commonly use for this type of application is the SRTM dataset. In the US, this is a 30 m resolution DEM covering the entire territory. Outside of the US it is 90 m resolution.

*Once you have your raster DEM you must make sure that it is hydrologically pre-processed. The interpolation method will generally introduce numerous artifact topographic depressions and possibly even flat areas. These are problematic because the grid cells contained in these features have no downslope neighbours, which is the whole basis for DEM flow-path routing. So you need to remove artefact depressions and flat areas from a DEM before performing flow analysis. In Spatial Analyst, your only option for this step is the Fill tool, although those who know me know that I much prefer depression breaching methods over filling.

*You then need to create a raster grid containing the information about flow directions, i.e. for each grid cell, which of it's eight neighbours does any water within the cell get directed towards. For this step you use the Flow Direction tool, which is based on the D8 flow algorithm. While the D8 algorithm is the most basic method for performing DEM based flow path analysis, it is appropriate for your application of watershed delineation (see here). Importantly, you must input the hydrologically corrected DEM from step 2 into the Flow Direction tool.

*Once you've created your flow direction grid (pointer) you can input it into the Flow Accumulation tool. This grid, again based on the D8 flow algorithm, will measure the size of the upslope area for each grid cell. While the flow direction grid isn't much to look at, the flow accumulation grid is a digital work of art. In particular, the grid cells with high flow accumulation will correspond nicely with streams and valley bottoms.

*Define your outlet cell, or what ESRI like to call a Pour Point. This is essentially the lowest point in your watershed; the point at the bottom to which all flow is directed. In the flow accumulation raster, an outlet is likely to correspond with a high-valued cell. You may get your pour point(s) in one of several ways. Perhaps you have GPS points of particularly areas of interest (e.g. a hydromet station where discharge and water quality are being monitored). Perhaps you want to extract the watershed for a particular tributary of a stream network, in which case you want the point directly above the confluence of your tributary of interest with the stream network. In this case, you would likely digitize your point of interest (pour point) from a vector stream network into a pour point vector file.

*Before you extract your watershed, you must ensure that your pour point coincides with the 'digital stream', i.e. the flowpath of high flow accumulation values in the flow accumulation raster. Even if your pour point falls off the digital stream by one grid cell, your extracted watershed will be extremely small, what I call a stub watershed (see here). So you need to use the Snap Pour Point to relocate the pour point onto the digital flowpath. You'll need to input that flow accumulation grid from step 4 here. Also, if you read that blog I linked to above, you'll see that I am not a fan of the Snap Pour Point tool, but using Spatial Analyst, it is your only option. In particular, you will need to be careful when using this tool if your pour point is anywhere near a confluence in a stream network because it is likely going to relocate the point downstream of the confluence and your extracted watershed will be much larger than you expect.

*Finally, you can use the Watershed tool to extract the watershed polygon(s) for the pour point(s). Afterwards, you may want to convert this raster watersheds to vectors so that you can overlay them nicely with other data.
It's a bit of an involved workflow but it is important that each step be completed properly otherwise you're very unlikely to get a satisfactory watershed at the end.

A: My advice for processing your data is to move from contour lines to a raster using Topo to Raster. From there, google ArcMAP watershed tutorial. It is a very common sample exercise in GIS courses. I found 9 course excerpts with that simple query.
Another recommendation is to get a trial version of AutoCAD Civil3D and calculate the watershed from a surface (probably a lot less steps to process than using ArcMAP).

A: It is possible to create a rough outline of a watershed boundary just using contours. You would pick a location (a "pour point"), usually in the stream channel so you might want to have a streams layer (you could get one like the NHD streams layer) or perhaps there are streams also on the CD. You would start at this one location (of your choosing) in the channel and run a line perpendicular to the contour lines and trace the highest elevations around until you go all the way around an area containing land that would drain to that "pour point". But that method is prone to error.
A better way is to automate the creation of a watershed with raster processing of Elevation data. If you have the Spatial Analyst Extension for ArcMap, this is a good recipe for you (this is the way I'm most familiar with). All the tools are in the Hydrology toolbox within the Spatial Analyst Toolbox. You can download free elevation data for the US from the NED program for example. The process involves a few steps but all that is needed is the pour point (or a series of points or even polygons ... the "watershed" command can also run on polygons). First you create a Flow Direction Grid (FDR) which can be made from the elevation dataset. Next you create a Flow Accumulation Grid (FAC) which can be made from the Flow Direction (FDR) output (actually that is an optional step). The FAC can be used to make a raster representation of the streams. Sometimes people use a process to "burn in" streams using a streams layer (like NHD) that forces the known stream representation to be the deepest areas within the elevation dataset (essentially forcing those areas to be the stream channels). The watershed command uses the FDR output as it's input and will delineate the watershed based on the direction of flow starting from your pour point(s) and working backwards to determine which cells in the landscape contribute flow to the point or points in question. Hope that helps!

A: hi you need to download dem form : hexplorer.usgs.gov
you need also ARCGIS with ARCHYDRO
ARCGIS : How to delineate watershed using ARC HYDRO?


text:
Q: Put datatable in new worksheet I'm trying to import a datatable into Excel using VB. I found tons of ways to do so, but all of them got an issue for me.
The first method I tried was using ClosedXML. It was great for importing data, but it messed up the pivot table. This is a known issue. Also, if the datatable is too big, it will throw and out of memory exception, another known issue.
Then I switched to Interop. But using Interop I only find one way to import the data, and that's with a double loop, as shown below. The issue for me here is, that it takes over 15 minutes to import a 3k rows, 39 columns table. This method seems slow and inefficient to me anyways, and I can't imagine Microsoft didn't implement a more effecive way to import larger datatables.
Is there someone who can show me a better method?
For i As Integer = 0 To datatable.Rows.Count() - 1
  For j As Integer = 0 To datatable.Columns.Count() - 1
    xlWorkSheet.Cells(i + 2, j + 1) = datatable.Rows(i)(j).ToString()
  Next
Next

Fadi's reply and a quick google search solved it for me.
    'dt is your Datatable and xlWorksheet is Your Worksheet
    Dim cc = dt.Columns.Count
    Dim rc = dt.Rows.Count

    Dim arr(rc - 1, cc - 1) As Object
    For r = 0 To rc - 1
        Dim dr = dt.Rows(r)
        For c = 0 To cc - 1
            arr(r, c) = dr(c).ToString 'I added ToString() here, because it raised an type error
        Next
    Next
    xlWorkSheet.Range("A2").Resize(rc, cc).Value = arr

A: Filling Excel range cell by cell is slow, You can create 2D Array and fill it from Datatable then assign this array to Excel range.
This code take 670 milliseconds in my test on Datatable with 3000 rows and 39 columns.
    'dt is your Datatable and xlWorksheet is Your Worksheet
    Dim cc = dt.Columns.Count
    Dim rc = dt.Rows.Count

    Dim arr(rc - 1, cc - 1) As Object
    For r = 0 To rc - 1
        Dim dr = dt.Rows(r)
        For c = 0 To cc - 1
            arr(r, c) = dr(c)
        Next
    Next
    xlWorkSheet.Range("A2").Resize(rc, cc).Value = arr

For Test:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim xl = New Excel.Application
    Dim wb = xl.Workbooks.Add()
    Dim xlWorkSheet As Excel.Worksheet = CType(wb.Worksheets(1), Excel.Worksheet)
    Dim dt = CreateDatatable()

    Dim cc = dt.Columns.Count
    Dim rc = dt.Rows.Count
    Dim tt = Now.Ticks

    Dim arr(rc - 1, cc - 1) As Object
    For r = 0 To rc - 1
        Dim dr = dt.Rows(r)
        For c = 0 To cc - 1
            arr(r, c) = dr(c)
        Next
    Next
    xlWorkSheet.Range("A2").Resize(rc, cc).Value = arr
    Dim ee = (Now.Ticks - tt) / 10000
    MsgBox(ee)
    xl.Visible = True
    xl.UserControl = True

End Sub

Function CreateDatatable() As DataTable

    Dim dt = New DataTable
    For c = 1 To 39
        dt.Columns.Add($"Col{c}")
    Next
    For r = 1 To 3000
        Dim dr As DataRow = dt.NewRow
        For c = 1 To 39
            dr(c - 1) = $"R{r},C{c}"
        Next
        dt.Rows.Add(dr)
    Next
    Return dt

End Function


text:
Q: Why does my websocket keep disconnecting in Django Channels App? I have been on this for a month now without a working solution. Everything works fine in production but I have been trying to deploy my django-channels application using nginx as reverse proxy, supervisor to keep servers running, gunicorn to serve http requests and I am stuck at the weboscket request part using daphne to process http requests.
I am bindig with unix sockets: gunicorn.sock and daphne.sock
The Console returns:
WebSocket connection to 'ws://theminglemarket.com/ws/chat/undefined/' failed:
Error during WebSocket handshake: Unexpected response code: 500

My supervisor config:
directory=/home/path/to/src
command=/home/path/to/venv/bin/gunicorn_start
user=root
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/path/to/log/gunicorn/gunicorn-error.log

[program:serverinterface]
directory=/home/path/to/src
command=/home/path/to/venv/bin/daphne -u /var/run/daphne.sock chat.asgi:application
autostart=true
autorestart=true
stopasgroup=true
user=root
stdout_logfile = /path/to/log/gunicorn/daphne-error.log

Redis server is up and Running, Sure of that, using redis-server
my nginx configurations:
upstream channels-backend {
#   server 0.0.0.0:8001;
    server unix:/var/run/daphne.sock fail_timeout=0;
}
upstream app_server {
    server unix:/var/run/gunicorn.sock fail_timeout=0;
}
server {
    listen 80;
    listen [::]:80;

    server_name theminglemarket.com www.theminglemarket.com;
    keepalive_timeout 5;
    client_max_body_size 4G;
    access_log /home/path/to/logs/nginx-access.log;
    error_log /home/path/to/logs/nginx-error.log;

    location /static/ {
        alias /home/path/to/src/static/;
        # try_files $uri $uri/ =404;
    }
    location / {
        try_files $uri @proxy_to_app;
    }
    location /ws/ {
        try_files $uri @proxy_to_ws;
    }
    location @proxy_to_ws {
        proxy_pass http://channels-backend;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
    }
    location @proxy_to_app {
        proxy_pass http://app_server;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        # we don't want nginx trying to do something clever with
        # redirects, we set the Host: header above already.
        proxy_redirect off;
    }
}

Please ask for any other thing needed, I'll update as quickly as I can. Thank You.
It's a chatting application, do you think I should use only Daphne, I'm considering the scalability, and that's why I used gunicorn to serve http requests. Hosting on Ubuntu Server

A: Try putting socket=tcp://0.0.0.0:8001  or socket=tcp://localhost:8001 in your [program:serverinterface] part of supervisord.conf. After that read your supervisor_log.log file to find out how it behaves. I had similar problems with it too. I hope that this helps. Use socket=tcp://localhost:8001 if it's inside of docker container. And make sure that nginx container is on the same docker network as that container.


text:
Q: Compute the difference percentage between rows using groupby in Python I have a dataframe df, and I would like to compute the difference percentage between the rows by group of week_number. The result should be the (last price - first price)/ first price in each week_number group.
For example, week_number 0, (95-100)/100 = 0.05 week_number 1, (80-24)/24 = 2.33 week_number 2, (96-37)/37 = 1.59  The count of each group of week_number is different.
I have no idea how to compute it using groupby method. Any help or hint would be appreciated.
value = [[100,0], [103, 0], [95, 0],
     [24, 1], [79, 1], [34, 1],[80, 1],
     [96, 2], [37, 2]]

df = pd.DataFrame(value, columns=['price','week_number'])

A: You can use the pipe function on the groupby, which allows you to reuse the groupby object:
    (df.groupby('week_number')
       .price
       .pipe(lambda df: (df.last() - df.first())/df.first())
       .abs()
     )

week_number
0    0.050000
1    2.333333
2    0.614583
Name: price, dtype: float64

The code above is about the same as the code below.
grouper = df.groupby('week_number')
top = grouper.last()
bottom = grouper.first()

top.sub(bottom).div(bottom).abs()

                price
week_number
0            0.050000
1            2.333333
2            0.614583

Again, the whole idea of pipe in this case is to reuse the groupby object

A: Try the following:
df.groupby('week_number')['price'].apply(lambda week: (week.iloc[-1] - week.iloc[0]) / week.iloc[0])

Output:
week_number
0   -0.050000
1    2.333333
2   -0.614583
Name: price, dtype: float64

To get the absolute value of your percentages change lambda to lambda week: abs((week.iloc[-1] - week.iloc[0])/week.iloc[0]) or append .abs() to the apply function df.groupby(...)[...].apply(...).abs()
If you want to see the result as percentages you can use this:
df.groupby('week_number')['price'].apply(lambda week: f'{(week.iloc[-1] - week.iloc[0])/week.iloc[0]:.3%}')


text:
Q: Overflow exception from SQL in only 64 bit applications I have an ODBC database running on an AS400. I have created a connection string to connect to the database and run queries. All of my queries run just fine when I compile the program to 32 bit but when I compile them to 64 bit I get an Overflow exception. Unfortunately I have to compile my program to 64 bit.
What could be causing this issue and how might I fix it?
More info:
The driver I'm using is iSeries Access ODBC Driver
All of my database columns are either strings or decimals
I am using a connection string not a DNS
The connection string I'm using is
"Driver={iSeries Access ODBC Driver};uid=XXX;data provider=ODBC;system=XXX;dbq=XXX;pwd = XXX"
I appreciate any help.
The code looks like this:
MPDCHFTableAdapter configs = new MPDCHFTableAdapter();
variants = configs.GetDataByProduct("98.M1BODY");

The stack trace is:
System.OverflowException was unhandled
  HResult=-2146233066
  Message=Arithmetic operation resulted in an overflow.
  Source=System.Data
  StackTrace:
       at System.Data.Odbc.OdbcDataReader.GetSqlType(Int32 i)
       at System.Data.Odbc.OdbcDataReader.GetFieldType(Int32 i)
       at System.Data.ProviderBase.SchemaMapping.SetupSchemaWithoutKeyInfo(MissingMappingAction mappingAction, MissingSchemaAction schemaAction, Boolean gettingData, DataColumn parentChapterColumn, Object chapterValue)
       at System.Data.ProviderBase.SchemaMapping..ctor(DataAdapter adapter, DataSet dataset, DataTable datatable, DataReaderContainer dataReader, Boolean keyInfo, SchemaType schemaType, String sourceTableName, Boolean gettingData, DataColumn parentChapterColumn, Object parentChapterValue)
       at System.Data.Common.DataAdapter.FillMappingInternal(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 schemaCount, DataColumn parentChapterColumn, Object parentChapterValue)
       at System.Data.Common.DataAdapter.FillMapping(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 schemaCount, DataColumn parentChapterColumn, Object parentChapterValue)
       at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)
       at System.Data.Common.DataAdapter.Fill(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
       at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
       at M3DataSorting.M3DataTableAdapters.MPDCHFTableAdapter.GetDataByProduct(String QIPRNO) in u:\Visual Studio 2012\Projects\M3DataSorting\M3DataSorting\M3Data.Designer.cs:line 8280
       at M3DataSorting.Program.update98SLURRY() in u:\Visual Studio 2012\Projects\M3DataSorting\M3DataSorting\Program.cs:line 314
       at M3DataSorting.Program.Main(String[] args) in u:\Visual Studio 2012\Projects\M3DataSorting\M3DataSorting\Program.cs:line 61
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

A: I'v found that using an OLE driver instead of ODBC prevents this problem from happening. Still not sure what the problem was though.


text:
Q: save gensim doc2vec trained model on google colab I am training text data using gensim doc2vec model on google colab repository GPU runtime, and want to save trained model in test.d2v file. following is code snippet
T = [TaggedDocument(doc, [i]) for i, doc in enumerate(data['info'])]
model = Doc2Vec(T,alpha=.025, min_alpha=.025, min_count=1)
model.save('test.d2v')

Following error is generated in colab notebook.
** /usr/local/lib/python3.6/dist-packages/smart_open/smart_open_lib.py:253: UserWarning: This function is deprecated, use smart_open.open instead. See the migration notes for details: https://github.com/RaRe-Technologies/smart_open/blob/master/README.rst#migrating-to-the-new-open-function
  'See the migration notes for details: %s' % _MIGRATION_NOTES_URL

A: A warning isn't necessarily an error, especially one that's just mentioning a 'deprecation'. Does your save file work? If so, it's safe to ignore this warning. See a prior answer for more details.


text:
Q: How to install or add qt QtSvg module to the statically built Qt framework My Qt5.7 is statically built with VS2015 in windows 10. The building configurations are as follows:
configure -static -debug-and-release -platform win32-msvc2015
-qt-zlib -qt-pcre -qt-libpng -qt-libjpeg -qt-freetype -opengl desktop
-qt-sql-sqlite -qt-sql-odbc -no-openssl -opensource -confirm-license
-make libs -nomake tools -nomake examples -nomake tests

It is found that the built Qt has no QtSVG module after I type QT += svg in a .pro file.  Does the building process build all Qt modules? I obtained the Qt source from here[qt official releases][1]
I want to add the QtSvg module, but do not want to rebuild the whole Qt, which is too time-consuming. Is there any simple way to add the module?
That is to install the module to the qtbase include folder, more specifically, C:\Qt\5.7.0\qtbase\include\QtSvg.


text:
Q: Reducible polynomials similar to Sophie Germain's identity Are there known any other simple nontrivial polynomials in two or more variables that can be factored like the one in Sophie Germain's identity?
$$x^4+4y^4=(x^2-2 x y+2 y^2) (x^2+2 x y+2 y^2)$$
Besides the well known (for $n \in \mathbb {Z} ^{+}$):
$$x^n-y^n=(x-y) \sum _{i=1}^n x^{i-1} y^{n-i}$$
$$x^{2 n-1}+y^{2 n-1}=(x+y) \sum _{i=1}^{2 n-1} (-1)^{i-1} x^{i-1} y^{2 n-1-i}$$
And of course besides trivial ones like $5 x^2+x y^2=x (5 x+y^2)$, where all terms share a common factor.
By simple polynomial I mean a polynomial that has few terms. The less terms the better - ideally only two terms like in the Germain's polynomial or in the known ones.

A: More formulas similar to Sophie Germain's identity can be derived from Aurifeuillean factorizations such as
$$x^6+27y^6=(x^2+3y^2)(x^2-3xy+3y^2)(x^2+3xy+3y^2),$$
$$x^{10}-3125y^{10}=(x^2-5y^2)(x^4-5x^3 y+15x^2 y^2-25x y^3+25y^4)(x^4+5x^3 y+15x^2 y^2+25x y^3+25y^4).$$

A: The roots of $\eta^3 - 3 \eta - 1 = 0$ are
$$  A = 2 \cos \left( \frac{7 \pi}{9} \right) \approx -1.532 \; \; \; , B =   2 \cos  \left( \frac{5 \pi}{9} \right)  \approx -0.347 \; \; \; , C = 2 \cos      \left( \frac{ \pi}{9} \right)  \approx 1.879 \; \; \; . $$
We get identity
$$ \color{magenta}{ (x+y+z)^3 - 9 \left( x^2 y + y^2 z + z^2 x \right) = (Ax+By+Cz)(Bx+Cy+Az)(Cx+Ay+Bz)  }  $$
There is a theorem: given a ternary cubic $f, \; $ write out the Hessian matrix $H.$ The entries of $H$ are homogeneous linear in the three variables.  As a result, the determinant $\Delta$ of $H$ is once again a ternary cubic. If $\Delta$ is a constant multiple of $f, \; $ then $f$ factors as the product of three homogeneous linear factors, although it might be necessary to allow complex coefficients. This all applies to Dietrich's example, where he does need complex coefficients.

A: For example,
$$
x^3+y^3+z^3-3xyz=(x+y+z)(x+\omega y+\omega^2z)(x+\omega^2y+\omega z),
$$
for a third root of unity $\omega$.


text:
Q: Транслировать строку из c# в php   byte[] hashedData = hmacGenerator.ComputeHash(tarrrr);
        byte[] codeArray = new byte[5];
        try
        {
            byte b = (byte)(hashedData[19] & 0xF);
            int Point = (hashedData[b] & 0x7F) << 24 | (hashedData[b + 1] & 0xFF) << 16 | (hashedData[b + 2] & 0xFF) << 8 | (hashedData[b + 3] & 0xFF);

            for (int i = 0; i < 5; ++i)
            {
                codeArray[i] = CodeTranslations[Point % CodeTranslations.Length];
                Point /= CodeTranslations.Length;
            }
        }

Собственно интересует как данная строка будет выглядеть в PHP.
Оригинал в C#

A: Исходя из предположения, что ваш hmacGenerator это SHA1 хеш (по длине в 20 байт подходит), получается так:
  $hashedData=sha1($tarrrr,true);
  $b=ord($hashedData[19]) & 0xF;
  $Point=unpack("N",substr($hashedData,$b,4))[1] & 0x7FFFFFFF;

  $arrLen=count($CodeTranslations);
  $codeArray="";
  for ($i = 0; $i < 5; $i++):
    $codeArray .= chr($CodeTranslations[$Point % $arrLen]);
    $Point = (int)($Point/$arrLen);
  endfor;


text:
Q: Can an applet be used with java web start? I was wondering if A Java applet can also use Java web start, I have been doing this in a project ive been working on an am worried that this may have caused some issues...

A: A hybrid approach offers more flexibility, easier debugging and a measure of clarity, but it is not required. But yes Applets can also be used as Java Web Start applications.
(answered by Andrew Thompson and trashgod)


text:
Q: HttpResponseMessage Create HttpStatusCode 550 At Http Response Common there is 550 Error, but I can not find it at HttpStatusCode Enumeration.
JavaScriptSerializer sr = new JavaScriptSerializer();
OTPOutError_Model oError = new OTPOutError_Model();
oError.message = "Business exception. ";

var httpContent = new StringContent(sr.Serialize(oError), Encoding.UTF8, "application/json");
var msg = new HttpResponseMessage(HttpStatusCode.HttpVersionNotSupported) { ReasonPhrase = "550", Content = httpContent };
throw new HttpResponseException(msg);

How can I return my Response Status 550? Is there any update of the enumeration?
At the sample code, I use 505 / HttpStatusCode.HttpVersionNotSupported. What I need is 550 instead of 505.


text:
Q: Js LocationPicker retrieving location data individually and apply to form http://logicify.github.io/jquery-locationpicker-plugin/#examples
I have a JS Googlemaps LocationPicker on my webpage, however I cannot make the autocomplete autofill the form.
Here is the code I am using:

Location
<input id="cityinput" name="City" type="text" class="my-form-control"
placeholder="Enter Your City"  required> </input>

<input id="citylat" name="citylat" type="text" class="my-form
control" placeholder="Enter Your Latitude" style="display:none;">
</input>

<input id="citylong" name="citylong" type="text" class="my-form-
control" placeholder="Enter Your Longitude" style="display:none;"></input>

  Building*
      <input id="address2" name="address2" class='my-form-control'/>

    City*
      <input id="locality" name="locality" class='my-form-control'required />

    State/Province*
      <input id="state" name="state" class='my-form-control' required />

    Postal code*
      <input id="postcode" name="postcode" class='my-form-control'required />

    Country/Region*
      <input id="country" name="country" class='my-form-control'required />

$('#us2').locationpicker({
    location: {
        latitude: 52.9470322,
        longitude: -1.1901637
    },
    radius: 50, addressFormat: 'locality',
    inputBinding: {
        locationNameInput: $('#cityinput'),
        latitudeInput: $('#citylat'),
        longitudeInput: $('#citylong'),

    },
    enableAutocomplete: true
});

Also I am aware that there is Json, but I am very new to json and not sure how to receive the json data.
Currently the full address is returned using
locationNameInput: $('#cityinput')

which appends to the div cityinput.
However to apply this to the address form i am struggling with as LocationPicker does not provide this, only the google Places API does.
I have been watching Youtube videos and reading the Google API and the JS locationPicker Docs, however I am still very unsure how to approach this.
I tend to work by finding working code then amend it for my own purposes, however I cannot find the code I need.


text:
Q: how to recover OSX files (failing drive) using a Windows PC? I need to recover some files from a failing drive (OSX, macbook drive) using Windows.
I dont have a Mac to work with.  Just a standalone drive that had osx installed.
What is the best way to do this?
I have access to a few revoery tools, recouva, getdataback, Paragon, etc.

A: Unless your utilities implicitly support HFS+ volumes, Windows wont work.  Windows cannot read HFS+ volumes out of the box.
You could boot off a Linux liveCD and install some of the free recovery tools onto a USB  drive.  I have used some of the Linux tools to recover files from a Mac.  Unfortunately, I dont remember which tool, but a Google search would suffice.

A: Thanks for the response Keltari.
I did some research on HFS+ tools and I found Paragon HFS+ .
this acts like a 'driver' in windows that allows read/write onto HFS drives.  once you plugin an hfs+ drive, it acts like any other external drive in explorer.


text:
Q: Is this training dataset enough for training and testing classification model? My training dataset contains just 2 classes with 40 features.
In case 1, class 1 has 35 samples and class 2 has 700 samples.
In case 2, class 1 has 65 samples and class 2 has the same value as above.
Is my training dataset enough for constructing the model using SVM classifier or some other classifiers?
I'm using WEKA. Testing options are 10-fold cross-validation and %66 and i get very good results.

A: You satisfied by result, so it means that you have enough data. It's hard to tell how much data you need, it depends on which problem you are solving exactly, how much noise in data you have, what features, etc.
I described it here in second part: https://stackoverflow.com/a/31567143/1030820


text:
Q: Memory leaks in pthread even if the state is detached I am learning pthreads programming.
I understood that there are two states of thread:
1. Joinable
2. Detachable
In case of Joinable, we need to call pthread_join to free the resources(stack), whereas in case of detached there is no need to call pthread_join and the resources will be freed on thread exit.
I wrote a sample program to observe the behavior
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

void *threadFn(void *arg)
{

 pthread_detach(pthread_self());
 sleep(1);
 printf("Thread Fn\n");
 pthread_exit(NULL);
}

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

 pthread_t tid;
 int ret = pthread_create(&tid, NULL, threadFn, NULL);

 if (ret != 0) {
  perror("Thread Creation Error\n");
  exit(1);
 }
 printf("After thread created in Main\n");
 pthread_exit(NULL);
}

When i try to check any mem leaks with valgrind it gave me leaks of 272 bytes. Can you show me why is the leak happening here.
$valgrind --leak-check=full ./app
==38649==
==38649== HEAP SUMMARY:
==38649==     in use at exit: 272 bytes in 1 blocks
==38649==   total heap usage: 7 allocs, 6 frees, 2,990 bytes allocated
==38649==
==38649== 272 bytes in 1 blocks are possibly lost in loss record 1 of 1
==38649==    at 0x4C31B25: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==38649==    by 0x40134A6: allocate_dtv (dl-tls.c:286)
==38649==    by 0x40134A6: _dl_allocate_tls (dl-tls.c:530)
==38649==    by 0x4E44227: allocate_stack (allocatestack.c:627)
==38649==    by 0x4E44227: pthread_create@@GLIBC_2.2.5 (pthread_create.c:644)
==38649==    by 0x108902: main (2.c:18)
==38649==
==38649== LEAK SUMMARY:
==38649==    definitely lost: 0 bytes in 0 blocks
==38649==    indirectly lost: 0 bytes in 0 blocks
==38649==      possibly lost: 272 bytes in 1 blocks
==38649==    still reachable: 0 bytes in 0 blocks
==38649==         suppressed: 0 bytes in 0 blocks
==38649==
==38649== For counts of detected and suppressed errors, rerun with: -v
==38649== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

A: Your expectation is correct that there shouldn't be any leaks in main thread once you call pthread_exit.
However, what you observe is a quirk of the implementation you're using (which is likely to be glibc) - pthreads library (glibc implementation) re-uses the initially allocated stack for threads - like a cache so that previously allocated stacks can be re-used whenever possible.
Valgrind simply reports what it "sees" (something was allocated but not de-allocated). But it's not a real leak, so you don't need to worry about this.
If you "reverse" the logic (main thread exits as the last thread) then you wouldn't see leaks because the initially allocated stack space is properly free'd by the main thread. But this leak isn't a real leak in any case and you can safely ignore this.
You can also setup a suppression file so that Valgrind doesn't complain about this (which is to inform Valgrind that "I know this isn't not real leak, so don't report this"), such as:
{
   Pthread_Stack_Leaks_Ignore
   Memcheck:Leak
   fun:calloc
   fun:allocate_dtv
   fun:_dl_allocate_tls
   fun:allocate_stack
   fun:pthread_create*

}


text:
Q: How to "pass on" a variable number of arguments to NSString's +stringWithFormat: I would like to write a function in Objective-C such as the one below, that takes a variable number of arguments, and passes those arguments on to +stringWithFormat:. I know about vsnprintf, but that would imply converting the NSString 'format' to C and back (and would also mean converting the formatting placeholders within it as well...).
The code below compiles, but of course does not behave as I want :)
NSString *estr(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *s = [NSString stringWithFormat:format, args];
    va_end(args);
    return s;
}

Basically: is there a va_list-friendly version of the +stringWithFormat: method, or is it possible to write one?

A: initWithFormat:arguments:
NSString *estr(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *s = [[[NSString alloc] initWithFormat:format arguments:args] autorelease];
    va_end(args);
    return s;
}

they don't seem to have a convenience constructor "stringWith..." version


text:
Q: Radio Buttons "Checked" Attribute Not Working The radio button does not show up as checked by default. I started off without a default choice doing some very simple js validation and it wasn't working. So I opted to just use default values until I figured that out and discovered that something weird is going on.
The markup is valid and I've tried in FF, Safari and Chrome. Nothing works.
I think it's a conflict with the jQuery library because the problem goes away when I remove the call script.

Do you want to accept American Express? Yes
<input id="amex" style="width: 20px;" type='radio' name='Contact0_AmericanExpress' value='1' /> No
<input style="width: 20px;" type='radio' name='Contact0_AmericanExpress' class='check' value='0' checked="checked" />

A: Hey I was also facing similar problem, in an ajax generated page.. I took generated source using Webdeveloper pluggin in FF, and checked all the inputs in the form and found out that there was another checkbox inside a hidden div(display:none) with same ID, Once I changed the id of second checkbox, it started working.. You can also try that.. and let me know the result.. cheers

A: Radio inputs must be inside of a form for 'checked' to work.

A: This might be it:
Is there a bug with radio buttons in jQuery 1.9.1?
In short: Don't use attr() but prop() for checking radio buttons. God I hate JS...

A: Just copied your code into: http://jsfiddle.net/fY4F9/
No is checked by default. Do you have any javascript running that would effect the radio box?

A: The jQuery documentation provides a detailed explanation for checked property vs attribute.
Accordingly, here is another way to retrieve selected radio button value
var accepted = $('input[name="Contact0_AmericanExpress"]:checked').val();

A: I could repro this by setting the name of input tag the same for two groups of input like below:

Header1

          <input type="radio" name="gender" id="male_1" value="male"> Male

          <input type="radio" name="gender" id="female_1" value="female" checked="checked"> Female

          <input type="submit" value="Submit">

Header2

          <input type="radio" name="gender" id="male_2" value="male"> Male

          <input type="radio" name="gender" id="female_2" value="female" checked="checked"> Female

          <input type="submit" value="Submit">

(To see this running, click here)
The following two solutions both fix the problem:

*

*Use different names for the inputs in the second group

*Use form tag instead of div tag for one of the groups (can't really figure out the real reason why this would solve the problem. Would love to hear some opinions on this!)

A: The ultimate JavaScript workaround to this annoying issue -
Simply wrap the jQuery command in a setTimeout.  The interval can be extremely small, I use 10 milliseconds and it seems to be working great.  The delay is so small that it is virtually undetectable to the end users.
setTimeout(function(){
  $("#radio-element").attr('checked','checked');
},10);

This will also work with

*

*$("#radio-element").trigger('click');

*$("#radio-element").attr('checked',true);

*$("#radio-element").attr('checked',ANYTHING_THAT_IS_NOT_FALSE);
Hacky...hacky...hacky...hacky... Yes I know... hence this is a workaround....

A: If you have multiple of the same name with the checked attribute it will take the last checked radio on the page.

<form>
    Do you want to accept American Express?
    Yes<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  />
    maybe<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  checked="checked" />
    No<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked="checked" />
</form>

A: hi I think if you put id attribute for the second input and give it a unique id value it will work
Do you want to accept American Express?
Yes<input id="amex" style="width: 20px;" type='radio' name='Contact0_AmericanExpress'   value='1'/>
No<input style="width: 20px;" id="amex0" type='radio' name='Contact0_AmericanExpress' class='check' value='0' checked="checked"/>

A:

**Radio button aria-checked: true or false one at a time**

$('input:radio[name=anynameofinput]').change(function() {
            if (this.value === 'value1') {
                $("#id1").attr("aria-checked","true");
                $("#id2").attr("aria-checked","false");
            }
            else if (this.value === 'value2') {;
                $("#id2").attr("aria-checked","true");
                $("#id1").attr("aria-checked","false");
            }
   });

A: also try this way
$('input:radio[name="name"][id="abcd'+no+'"]').attr("checked", "checked");

if there is <form /> tag then ("checked", true) otherwise ("checked", "checked")

A: Your code is right, try to debug your JQuery script to find the issue!
If you're using FF you can install an extension to debug JS (and JQuery) it's called FireBug.

A: You're using non-standard xhtml code (values should be framed with double quotes, not single quotes)
Try this:
<form>
  Do you want to accept American Express?
  Yes<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  />
  No<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked="checked" />
</form>

A: just add checked attribute to each radio that you want to have default checked
try this :
<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked/>

A: Replace checked="checked" with checked={true}. Or you could even shorten it to just checked.
This is because the expected value type of the checked prop is a boolean. not a string.


text:
Q: Updating Task level custom fields Using CSOM I can see how to use the SetCustomFieldValue method to update custom fields associated to a Project, but is it not possible to do this for a task within Project Online? I don't see anything that would allow this but it does list in the documentation this should be possible.
Thanks!

A: Have you looked at this thread?
Use CSOM to update project's custom fields
It's Project level but it may provide some further clues.
Actually, there's task level code at the bottom of that post so hopefully, that's what you need.

A: I've also searched for a way of updating task level custom fields, but couldn't find a solution.
For this and some other reasons I've decided to do this by implementing a projectdrilldown extension. This means to update the value directly in the project grid and let project server do the rest of the internal processing:
       _grid=window.projectDrilldownComponent.get_GridSatellite(); // get the grid

       // Update the datavalue of a column (taskfield)
       _grid.WriteDataValueByKey(...)
       // Update the localizedvalue of a column (taskfield)
       _grid.WriteLocalizedValueByKey(rec_key, fieldkey, fieldvalue,
                function () {
                    console.log("Post Update task:" + rec_key);
                    cbSuccess();                        // callback after update                     });

A: I can give you a JSOM example to do this:
var projContext = PS.ProjectContext.get_current();
var projects = projContext.get_projects();
var project = projects.getByGuid(projUid).get_draft();
var tasks = project.get_tasks();

var task = tasks.getByGuid(taskUid);

task.set_item(cfIntName, newValue);

var queueJob = project.update();

projContext.waitForQueueAsync(queueJob, 60,
    Function.createDelegate(this, function(res) {
        // Publish project here
    }), function(error) {

    console.error(error);
});

That should be complete (though I pulled it from a script, so check the success / failure handlers which I truncated)
From memory poking around in the CSOM there is no "set_item(cf, val)" helper method to use, but it was similar, I think the property is set on the object instance via an indexer, e.g.:
(sudo c# code)
var draftTask = [get task instance];
draftTask[cfInternalName] = "Some value";

etc.
If that doesn't help then you can always reflect the ProjectServer.Client.DLL and you'll see the internal implementation of "SetCustomFieldValue" which is not publicly exposed.
Hope that helps someone.


text:
Q: "HTTPError: 429 Client Error: Too Many Requests for url" in Python [w/ Azure developer account] Getting continual exception when trying to run Python code on a small sample directory of 5-20 images.
I have a developer account with Microsoft (as of this morning) and have inquired with Azure Support, but this issue wasn't solvable through chat alone. They've instructed me to post this here, so I'm sorry if it comes off as an eye-roll to everyone else!
There's very little documentation on this web-wide. Maybe this'll help someone else, because this is potentially a game-changer for people in graphics and media who have a huge amount of disorganized images like I do.
Note that this code DID work once last night! But only once. No idea what went wrong!
# API reference :

# https://westus.dev.cognitive.microsoft.com/docs/services/5adf991815e1060e6355ad44/operations/56f91f2e778daf14a499e1fa

# 参考 : https://ledge.ai/microsoft-computer-vision-api/

# 機能概要 : img フォルダ中の画像をAI解析し、ファイルのリネームを行います。

# 使い方 : python3 cv_demo.py

# 注意 : サブスクリプションキーは変更してください

import requests

import glob

import os

import time

import urllib

subscription_key = "i do have a real subscription key don't worry"

assert subscription_key

vision_base_url = "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/"

analyze_url = vision_base_url + "analyze"

# ファイル名を変更

def file_rename(list_1, list_2):

    for i in range(len(list_1)):

        os.rename(list_1[i], './img/' + list_2[i] + '.jpg')

def ms_computer_vision_api(filepath):

    headers = {'Ocp-Apim-Subscription-Key': subscription_key,'Content-Type': 'application/octet-stream'}

    params = urllib.parse.urlencode({
    # Request parameters
   'visualFeatures': 'Categories,Tags,Description,Faces'
   })

    img = open(filepath, 'rb')

    img_byte = img.read()

    response = requests.post(analyze_url, data=img_byte, headers=headers, params=params)

    response.raise_for_status()

    return response.json()

if __name__ == "__main__":

    # 画像ファイルを配列に格納

    image_file = glob.glob('./img/*')

    vision_file_name = []

    start = time.time()

    # Computer Vision APIにリクエストして結果を取得

    for i in range(len(image_file)):

        json_data = ms_computer_vision_api(image_file[i])

        # 生成された文章を取得

        file_name = json_data['description']['captions'][0]['text']

        vision_file_name.append(file_name)

    # 文章の空白をファイル名用にアンダーバーに修正

    for i in range(len(vision_file_name)):

        vision_file_name[i] = vision_file_name[i].replace(' ', '_')

    file_rename(image_file,vision_file_name)

    # 経過時間を出力

    print("elapsed_time:{0}".format(time.time() - start) + "[sec]")

 File "C:\Users\MyName\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\requests\models.py", line 940, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 429 Client Error: Too Many Requests for url: https://renameimages.cognitiveservices.azure.com/vision/v2.0/analyze?visualFeatures=Description

A: Based on your code this error comes from a loop which requesting a cognitive API.
Actually each Cognitive Service has the limit of TPS (Transaction Per Second), and will report 429 error when exceed the TPS. Even if specific Cognitive Service has a higer TPS such as 50 TPS, maybe you still have 429 error. You should always use the following policy to avoid 429 in the future.
The following is the explanation 429 and how to handle 429.

*

*HTTP 429 would indicate RateLimitExceeded, meaning you are making too many API calls per second or minute.

*When HTTP 429 happens, you must wait for some time to call API again, or else the next call of API will be refused. Usually we retry the operation using something like an exponential back off retry policy to handle the 429 error:
2.1) You need check the HTTP response code in your code.
2.2) When HTTP response code is 429, then retry this operation after N seconds which you can define by yourself such as 10 seconds…
For example, the following is a response of 429. You can set your wait time as (26 + n) seconds. (PS: you can define n by yourself here, such as n = 5…)
{
    "error":{
       "statusCode": 429,
        "message": "Rate limit is exceeded. Try again in 26 seconds."
    }
}

2.3) If step 2 succeed, continue the next operation.
2.4) If step 2 fail with 429 too, retry this operation after N*N seconds (you can define by yourself too) which is an exponential back off retry policy..
2.5) If step 4 fail with 429 too, retry this operation after NNN seconds…
2.6) You should always wait for current operation to succeed, and the Waiting time will be exponential growth.


text: Q: How to design project solution for webapi2 with angularjs project? I am starting new project with angularjs with webapi. This project will be e-commerce site. There is iOS and Android app also. We are going to develop APIs so that Android and iOS team can consume our APIs. Also we are going to consume APIs using angularjs for web application. I need some inputs before starting project. I am planning to design separate solutions for APIs and my web application. I am using visual studio for development environment for front end. I am confused about which template should I use in vs2015 to develop front end? My front-end will contains angular js files,HTML pages and CSS files. Second point is there is a Arabic version of this website so I am storing all Arabic words in resource file. Where should I store my resource files? In API project or front end project? May I get some inputs to develop solution architecture? Also what is the standard way of angularjs project folder structure? Any help would be appreciated. Thank you.


text:
Q: Hide downloads from download manager android I am implementing a mp3 downloader for android. I am using native DownloadManager service. Obviously, when I download a file, it also shows the downloading(or downloaded) file in the Download Manager app. I want to hide the downloaded file from Downloaded Manager i.e. I don't want the file to be displayed in the download manager list. Is there any way to acheive this?

A: Try setVisibleInDownloadsUi() on your DownloadManager.Request.


text:
Q: why my XFS file system got corrupted? root cause analysis I have a block SAN storage volume mounted to my server via FC, I have formatted the volume with XFS.
I started experiencing file system corruption that can be easily repaired with xfs_repair, however I'm unable determine the root cause of the issue.
I'm positive it has nothing to do with my FC storage as other connected servers are operating normally.
Is there is logs / package I need to use to determine the root cause of such issue?
Environment RHEL 6.7
Thanks


text:
Q: MembershipUser.ChangePassword returns false at all times Using System.Web.Providers.DefaultMembershipProvider along with System.Web.Security.MembershipUser, I am attempting to change a users password in the databases. For some reason, no matter what I do, the MembershipUser.ChangePassword(old, new) returns false with no errors.
In the database, my ApplicationID that is associated to the Application name is correct, and my user has that ApplicationID attached to it in both the Memberships and Users tables. The User is not null when it comes to that point, all the data is accurate in the object. I am at a complete loss here, any help would be greatly appreciated as no other source has been able to help me.
EDIT:
User is not locked out, the user is active, and the password is correct. All
password requirements are being fulfilled. This is extremely frustrating since
the MembershipUser.GetUser() finds the user and all of its associated data but
will not change the password.

Additional Steps:
    - Tried MembershipUser.UnlockUser() just in case, no luck.
    - Tried MembershipUser.ResetPassword() then a change. This fails with the
      error message "Value cannot be null" even though it should be able to.
    - GetSpecificVerion of the entire solution and working to when it first
      broke. Every version worked, including my latest (Yay!), but then it
      magically stopped working again a few minutes later, no code changes
      were made at all.

Bounty added, looking for any and all possibilities that could lead to a fix...

Config File:
----
<add name="aspnetdb" connectionString="Application Name=appname;Type System Version=SQL Server 2008;server=***,****;Initial Catalog=aspnetdb;Integrated Security=false;pwd=****;user id=****" providerName="System.Data.SqlClient" />
----

----
<membership defaultProvider="DefaultMembershipProvider">
    <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="aspnetdb" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" passwordAttemptWindow="10" applicationName="mysite.com" />
    </providers>
</membership>
----

Method:
public ActionResult ChangePassword(ChangePasswordViewModel model)
{
    // Indicates whether changing the password was successful or not.
    Boolean passwordChanged = false;

    if (ModelState.IsValid)
    {
        // Grab the current user.
        MembershipUser user = Membership.GetUser(User.Identity.Name, true);

        if (user != null)
        {
            passwordChanged = user.ChangePassword(model.OldPassword, model.NewPassword);
        }
    }

    return Json(new { Success = passwordChanged });
}

A: Turns out someone else within the company was using the same DEV database to back an internal OpenID Provider. During the development of this OpenID Provider, the data was getting altered causing odd behavior. Thankfully I just happened to notice some data change on me and ask some questions of the other groups, saved me from wasting any more time..
This is still odd that I was able to retrieve a user but not change the password of that user. In the end, clearing up the communication between the two projects seems to have cleared up the issue for now.
Nice lesson learned here when sharing a database. Thanks for those of you who tried to help :)


text:
Q: Scala.js implicit conversions don't work... sometimes? I can't quite understand why implicit conversions from Scala to JS values don't work this way:
Scala Fiddle
import scala.scalajs.js
import scala.scalajs.js.JSConverters._

trait X extends js.Object {
  def map(f: js.Function1[Int, String]) = js.native
  def mapScala(f: Function1[Int, String]) = js.native // just for demo purpose, this is not really part of type X
  def create(maybe: js.UndefOr[Int]) = js.native
}

def test(x: X) {
  // I want these two lines to compile, but they don't
  x.map(a => "yo") // error: missing parameter type
  x.create(None) // error: type mismatch. Found None.type, required: js.UndefOr[Int]

  // This works, but is too verbose
  x.map((a: Int) => "yo") // only if arg type specified like this
  x.mapScala(a => "yo") // because mapScala expects a Scala Function1
  x.create(JSRichOption(None).orUndefined) // because value is manually converted
}

Am I trying to use implicit conversions the wrong way? The implementation of class X is provided externally, in Javascript. In my code I want to pass native Scala values to methods of X, I don't want to do the conversion manually each time.
I know there's an alternative way for Scala.js – to pimp my type X like this, but I'm trying to avoid that because it's more boilerplate and a lot more objects will be instantiated at runtime that way. Regardless of that, I still do want to understand why exactly my code isn't working.

A: The reason the map call does not work is a limitation in Scala's type inferencer: It needs to resolve the full type before looking for implicit conversions. However, Scala 2.12 brings SAM treatement just like Java. Roughly that means that you can write a lambda in stead of an anonymous class implementing an interface with a single method.
So x.map(a => "yo") will expand into:
// Never (!) write this yourself.
x.map(new js.Function1[Int, String] {
  def apply(a: Int): String = "yo"
})

Which the Scala.js compiler handles separately. You can enable SAM treatment in Scala 2.11 with the -Xexperimental flag.
The reason the create call does not work is that there is no implicit conversion (in the Scala.js standard library) from Option[T] to js.UndefOr[T]. There is an implicit conversion to JSRichOption[T] which enables the orUndefined method. You should write:
x.create(None.orUndefined)

Or in this case, you can simply write:
x.create(js.undefined)


text:
Q: LDAP users trying to authenticate get error 50 Insufficient access (openldap) After our ldap database suddenly became corrupt for no obvious reason, I had to restore an older database. This seemed to have worked, and I am able to access, browse and even update entries in the LDAP using an LDAP explorer client. Browsing entries is even possible anonymously.
However, applications that are trying to authenticate users against the LDAP, now fail with LDAP: error code 50 - Insufficient Access Rights
I can reproduce the issue using ldapwhoami:
$ ldapwhoami -vvv -h ldap.localnet -D
'uid=username,cn=users,dc=unimatrix1,dc=localnet' -x -W
ldap_initialize( ldap://ldap.localnet )
Enter LDAP Password:
ldap_bind: Insufficient access (50)

I get the same result when trying this with a newly added user. So I assume that an ACL is missing or wrong, however, I haven't made any changes to them, and the ldif files still date to 3 years ago.
How do I re-establish authentication for all users in LDAP?
It's Open Directory on macOS Sierra (OpenLDAP-523.30.2), in case that matters.

Addendum
There is this entry as the last one in /etc/openldap/slapd.d/cn=config/olcDatabase={1}bdb.ldif
olcAccess: {22}to *  by set.exact="user/uid & [cn=admin,cn=groups,dc=unimatrix
 1,dc=localnet]/memberUid" write  by dn.base="uid=_ldap_replicator,cn=users,dc
 =unimatrix1,dc=sssnet" write  by sockurl.exact="ldapi://%2Fvar%2Frun%2Fldapi"
  write  by * read

I suppose I should somehow add by anonymous auth before by * read?
There's also this entry which I'm not sure of if that affects authentication?
olcAccess: {14}to dn.one="cn=computers,dc=unimatrix1,dc=localnet"  attrs=entry
 ,apple-realname,cn,description,macAddress,authAuthority,userPassword  by set.
 exact="user/uid & [cn=admin,cn=groups,dc=unimatrix1,dc=localnet]/memberUid" w
 rite  by sockurl.exact="ldapi://%2Fvar%2Frun%2Fldapi" write  by dnattr=creato
 rsName write  by * read

Update
I just found out that, using ApacheDirectoryStudio, I can authenticate using 'CRAM-MD5 (SASL)', but I get error 50 if I select 'Simple authentication'. I was able to verify it using ldapwhoami like this:
$ ldapwhoami -vvv -h ldap.localnet -U username -W
ldap_initialize( ldap://ldap.localnet )
Enter LDAP Password:
SASL/SRP authentication started
SASL username: username
SASL SSF: 256
SASL data security layer installed.
dn:uid=username,cn=users,dc=unimatrix1,dc=localnet
Result: Success (0)

So now it looks to me as if the LDAP used to allow Simple authentication, but has somehow lost this configuration when I restored the database. I don't even know where and how this is configured?

A: The problem may occur when UniqueID in the restored LDAP data differ from the uid used by the system (for whatever reason).
To verify if that is the problem, check the user entry in the LDAP for the value in the UniqueID attribute.
Then open a shell on the server and check uid used there:
$ id -u username
1003

If applicable, you may also take a look at the home directory of the use with uid displayed (option -n). For example (on macOS the home directories are in /Users):
$ ls -aln /Users
drwxr-xr-x+  18 1003  20    612 Jun  5  2018 username

If the ids are not identical, then change the UniqueID in the LDAP data to match the uid of the user.
Alternatively, you may try to change the owner of the home directory
$ chown -R username /Users/username

but the uid may be have been used in other areas of the system, so the preferred way is to change UniqueID in the LDAP entry.


text:
Q: Grow heap (frag case) to 8.837MB for 6220816-byte allocation error I am trying to use 15 to 20 images to show on livewallpaper background one by one on a fix time ,but I am facing grow heap problem (Grow heap (frag case) to 8.987MB for 6220816-byte allocation) I have search everything but couldn't get through this
Any help pleas.
here is my code
public class LiveWallpaperService extends WallpaperService {
private float x;
private int y;
private int angle;
private int speed;

@Override
public void onCreate() {
    super.onCreate();
}

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

@Override
public Engine onCreateEngine() {
    stopSelf();
    return new MyWallpaperEngine();
}

class MyWallpaperEngine extends Engine {

    private final Handler handle = new Handler();
    private final Runnable drawRunner = new Runnable() {

        @Override
        public void run() {
            draw();
        }
    };

    private Boolean visble = true;
    public Bitmap mBackgroundImage;
    public String name;
    int[] mImagesArray;
    private int mImagesArrayIndex = 0;

    MyWallpaperEngine() {

        mImagesArray = new int[] { R.drawable.love_1_mini,
                R.drawable.love_2_mini, R.drawable.love_3_mini,
                R.drawable.love_4_mini, R.drawable.love_5_mini,

                R.drawable.love_6_mini, R.drawable.love_7_mini,
                R.drawable.love_8_mini, R.drawable.love_9_mini,
                R.drawable.love_10_mini,

                R.drawable.love_11_mini, R.drawable.love_12_mini,
                R.drawable.love_13_mini, R.drawable.love_14_mini,
                R.drawable.love_15_mini, R.drawable.love_16_mini,
                R.drawable.love_17_mini, R.drawable.love_18_mini,
                R.drawable.love_19_mini, R.drawable.love_20_mini };

        if (mImagesArrayIndex == 0) {
            x = -330; // initialize x position
            y = 0; // initialize y position
        } else {
            x = -330; // initialize x position
            y = 0; // initialize y position
        }

    }

    @Override
    public Bundle onCommand(String action, int x, int y, int z,
            Bundle extras, boolean resultRequested) {
        return super.onCommand(action, x, y, z, extras, resultRequested);
    }

    @Override
    public void onCreate(SurfaceHolder surfaceHolder) {
        super.onCreate(surfaceHolder);
    }

    @Override
    public void onOffsetsChanged(float xOffset, float yOffset,
            float xOffsetStep, float yOffsetStep, int xPixelOffset,
            int yPixelOffset) {
        draw();
    }

    @Override
    public void onSurfaceCreated(SurfaceHolder holder) {
        super.onSurfaceCreated(holder);
        this.visble = false;

    }

    @Override
    public void onTouchEvent(MotionEvent event) {

    }

    @Override
    public void onVisibilityChanged(boolean visible) {
        this.visble = visible;
        if (visible) {
            handle.post(drawRunner);
        } else {
            handle.removeCallbacks(drawRunner);
        }

        super.onVisibilityChanged(visible);
    }

    private void incrementCounter() {
        mImagesArrayIndex++;
        if (mImagesArrayIndex >= mImagesArray.length) {
            mImagesArrayIndex = 0;

        }

    }

    @SuppressWarnings("deprecation")
    void draw() {

        int count = mImagesArray[mImagesArrayIndex];
        final SurfaceHolder holder = getSurfaceHolder();
        Canvas c = null;
        int scale = 2;
        Resources res = getResources();
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inPreferredConfig = Bitmap.Config.RGB_565;
        o2.inSampleSize = scale;
        o2.inPurgeable = true;
        o2.inInputShareable = true;
        Bitmap image = BitmapFactory.decodeResource(res, count, o2);

        Calendar mCalendar = Calendar.getInstance();
        int h = mCalendar.get(Calendar.HOUR);
        int m = mCalendar.get(Calendar.MINUTE);
        int s = mCalendar.get(Calendar.SECOND);

        if (s == 10) {
            mImagesArrayIndex = 0;
        }

        try {
            Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
            c = holder.lockCanvas();
            c.drawColor(Color.RED);

            if (c != null) {
                int a = 0;
                int counting = 0;
                if (counting == a) {
                    a++;
                    counting++;

                    c.drawBitmap(image, x, y, paint);

                    int widthhhh = c.getWidth();

                    x = (float) (x + 10.10);

                    if (x > widthhhh + 400) {

                        image.recycle();
                        image = null;
                        incrementCounter();

                    }

                }

                paint.setColor(Color.RED);

            }

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {

            try {
                if (c != null) {
                    holder.unlockCanvasAndPost(c);
                }
                handle.removeCallbacks(drawRunner);
                if (visble) {
                    handle.postDelayed(drawRunner, 10);
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

}

}

A:
Bitmap image = BitmapFactory.decodeResource(getResources(), mImagesArray[mImagesArrayIndex]);

When your done with it call image.recycle() (see javadoc).

A: In your draw() method, you have this code:
    Bitmap image = BitmapFactory.decodeResource(getResources(),
            mImagesArray[mImagesArrayIndex]);
    int count = mImagesArray[mImagesArrayIndex];
    final SurfaceHolder holder = getSurfaceHolder();
    Canvas c = null;
    int scale = 4;
    Resources res = getResources();
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inPreferredConfig = Bitmap.Config.RGB_565;
    o2.inSampleSize = scale;
    o2.inPurgeable = true;
    o2.inInputShareable = true;
    image = BitmapFactory.decodeResource(res, count, o2);

Notice the first line calls BitmapFactory.decodeResource() and assigns the result to variable image and then later, the last line again calls BitmapFactory.decodeResource() and assigns the result to variable image. You never called recycle() on the first decoded image, so this is giving you a memory leak.


text:
Q: How do I mimic a native 404 page? I'm trying to 'soft shutdown' a website so users see an offline 404 page, but actually keeping the web server there.
Most of the solutions I found for 404 pages were creating custom (beautiful) 404 pages. I want to do the opposite: mimic a browser's stock (native) 404 page as close as possible.
So far I've tried the below.
In .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteRule ^ notfound.php [L]
</IfModule>

and in notfound.php
http_response_code(404);
die();

The code works for Chrome and Firefox (showing a native 404 page), but Safari shows a blank (white) page instead. Is there a better way to address this?


text:
Q: Omnikey for Safari 13? Omnikey is a very useful Safari extension that allows searching user-selected webpages by entering user-selectable keys preceding the search term. For example, entering "w Los Angeles" in the Safari address bar on my computer and pressing return opens a new Safari window in Wikipedia that's searching for "Los Angeles." This is both easier and faster than navigating to the page you wish to search, entering the search term, then hitting return.
Here's a screenshot of the searches I've added to Safari on my Macs:

Unfortunately, Omnikey doesn't work with Safari 13.
Omnikey is very useful. Are there any other Safari extensions that provide the same functionality?

A: I was totally bugged out by the lack of Omnikey after upgrading to Safari 13.
This applescript saved my life (it's not mine so I'm just posting the link):
https://macscripter.net/viewtopic.php?id=47107
In order to activate it, open Automator, create a new Quick Action, select "Run Applescript" from the action list on the left side of the window, and copy/paste the script to the editor window. Above the editor window, change "Workflow receives" to "no input" and save.
Then go to System Preferences, keyboard, shortcuts, and assign a keyboard shortcut to it. Now, when in Safari's address bar you can just press the shortcut and the script transforms the search to the right URL, e.g. type "we apple", press the shortcut, services, and the wikipedia article about "Apple" opens in the same Safari tab.
In order to add more searches, just edit the script in the "property shortcuts" section, it looks pretty self-explanatory to me. Now searching from the address bar works almost as before, just have to get used to pressing the shortcut instead of return.

A: I was missing this very same functionality. In response, I created a small extension for Safari 14, replacing this functionality: Smart Keyword Search.
(I did today also stumble upon another extension claiming to do the same: Search Key -- I do feel that Smart Keyword Search allows for more options, and has better documentation, but I cannot be considered objective I guess :)).

A: As OP informed, restarting after reverting using backup restore made Safari accept the Omnikey as an extension. They are on Safari 12.1.2.
The post below may concern those looking for more ways to achieve the same.

*

*Omnikey can be used in the browser by fooling the browser (Safari 12.1.1) into believing that you're developing the extension(that's what I can make of it).

*

*Load it using Show extension builder in Develop menu in the form of an folder which you can get by expanding the .xar version of the extension file which you can get from the site. Note that to get .xar from extension file, simply use rename feature.

*Then just hit run. For details about updating previous preferences, or understanding it in more clarity, see original post by georgegarside at
https://georgegarside.com/blog/macos/install-any-safari-extension-macos-mojave/
But for alternatives:

*Safari has inbuilt Quick Website Search, you just have to figure out the term that triggers it. Find out more in  Safari Preferences
→ Search tab → Quick Website Search. Results are like this.

*Use DuckDuckGo's !bangs .

A search for !w filter bubble will take you directly to Wikipedia. [...] and you can even submit your own.

source:https://duckduckgo.com/bang
https://computers.tutsplus.com/tutorials/how-to-set-up-custom-searches-in-safari--cms-26139 explains in detail those alternates that I figured out.


text:
Q: Como que faço para que o calendário comece na segunda?      <?php
        function linha($semana){
            echo "
";

            for ($i=0; $i<=6; $i++):
                if(isset($semana[$i])):
                    echo "$semana[$i]	";
                else:
                    echo " 	";
                endif;

            endfor;

            echo "
";
        }

        function calendario(){
            $dia = 1;
            $semana = array();
            while ($dia <= 31):
                array_push($semana,$dia);

                if(count($semana)== 7) :
                    linha($semana);
                    $semana = array();
                endif;

            $dia++;

            endwhile;

            linha($semana);

        }
     ?>

                 Dom
                 Seg
                 Ter
                 Qua
                 Quin
                 Sex
                 Sáb

           <?php calendario() ?>

A: Você consegue pegar o primeiro dia da semana com date("d/m/Y H:i:s", strtotime(date("Y")."W".date("W"))); (Não se esqueça de definir o date_default_timezone_set()).


text:
Q: Forced oscillations Suppose we are using a pendulum.
From one extremity we just leave it, it reaches the other extremity and again reaches us at a certain time period. We will be able to apply the next force to it when it reaches us after a certain time period and hence we will be able to account for the damping force which it experiences.
This simply means that we are applying a force at a frequency which is equal to the natural frequency of the vibrating body.
But if we now apply a force at a frequency which is other than the natural frequency of the vibrating body, it is written in our book that its amplitude decreases. I searched for this doubt and I got that as the force is not in the same frequency as the natural frequency of the vibrating body the force is not applied at the time when the body is at the vicinity of the force. And so due to damping force its amplitude decreases, but we were said that a vibrating body acquires the frequency of the external periodic force, so the force should act at the correct point of time when the body is in its vicinity; as a result its amplitude should increase rather than decrease, but we do not find it so. Why?
I request you give a lucid explanation to this because I am a tenth grade student. Please don't use any complicated terminologies.

A: You seem to be considering what happens when you apply pulses of force (that is forces for very short periods of time). This is what you might do when pushing a child on a swing in order to increase the amplitude of swing. It then seems obvious that to get the maximum amplitude you need to apply the pulses at the natural frequency, $f_0$, of the swing (and at the 'right' point in its cycle) so that the natural oscillations are 're-inforced'.
The resonance curves that you see in textbooks are not drawn for pulsed forces (applied to a system with its own natural frequency). Indeed it is clear that you won't get the classic shape of curve if you use such forces. For suppose you apply a pulse at a frequency $f_0/2$, that is once every two cycles of natural oscillations. This will also lead to an increase in amplitude, so the resonance curve will have another peak at frequency $f_0/2$. There will be further peaks at each subharmonic ($f_0/n$).
Resonance curves, as usually understood, are drawn for the case of an applied force which varies smoothly throughout the cycle, a so-called 'sinusoidally' varying force. In this case there is only a single peak to the resonance curve. [It's more useful to consider a sinusoidal force that a series of regular pulses because it's extremely convenient to regard any shape of oscillation as a sum of sinusoids of different frequencies  and amplitudes.] Unfortunately, though, with a sinusoidal driving force it's harder to get a simple intuitive feel for why the resonance curve has exactly the shape it does. Instead we use Newton's second law and proceed using mathematics.

A: So if I understand correctly we have a pendulum and we are pushing it for only a small time period every oscillation. Like pushing a child on a swing where the duration of the force is small compared to the period of the swing.
For example let's take a pendulum with a natural period of 1s. So if you leave it alone it completes a cycle every second. Now if we push it with a slightly larger period, say 1.1s, the following happens: when we push we will be late. So during some oscillations our push will be 'in phase' with the pendulum and during others our push will be 'out of phase'. With 'in phase' I mean that my push is in the same direction as the motion of the pendulum. In the example of the swing this would be pushing the child when it starts to move down. Out of phase means the opposite. It would be like pushing the kid when it comes towards me.
During the 'in phase' pushes I will be adding energy to the system so the amplitude will grow larger and during the 'out of phase' pushes I remove energy from the system and the amplitude will go down. Because my frequency of pushing doesn't match the natural frequency of the pendulum whether I'm in or out phase changes. Correspondingly the amplitude will grow bigger and smaller.
If you consider the largest amplitude that you achieve as a function of driving frequency you will get that the closer you are to the natural frequency, the larger the amplitude will be. In physics we often consider a simpler type of driving force $F_{drive}(t)=A\sin(2\pi f_{drive}t)$ where $f_{drive}$ is the driving frequency. It sounds more complicated but when you plug it into the math it actually becomes easier. You can then make the following plot

In the plot $\zeta$ means the amount of friction. On the horizontal axis you see the driving frequency where 1 corresponds to the natural frequency. On the vertical axis you see the amplitude after the system has reached steady state. Steady state means that the waited long enough so the oscillation doesn't change anymore. The nice thing is that, for a perfect pendulum, if you drive it using a sinusoidal force the motion will also be a sine wave (in steady state). In steady state the frequency of the motion is the same as the driving frequency.
Note: in the plot you can see that for very low frequencies the amplitude is still one. In this case the pendulum follows the driving force. It is like you are pushing a swing so slowly that you are basically moving the kid without any swinging happening.
Note 2: I'm not sure what the resulting frequency will be when you force for small periods of time like in your question. This case is actually considerably harder than the sinusoidal case.

A: A resonant driving force will cause the amplitude to increase until some damping force (such as friction) removes energy as fast as it is being added.  There is an infamous example:  On a very windy day a long suspension bridge near Tacoma started to oscillate (standing torsional waves).  The changes in shape caused the forces from the wind to get into resonance.  The damping forces were inadequate, and the bridge came apart.


text:
Q: Why do we have $\mu_* \mathcal{O}_Y(K_{Y/X}) = \mathcal{O}_X$ for a resolution? Let $X$ be a normal complex variety and $\mu : Y \to X$ a resolution of singularities. We define the relative canonical divisor to be $K_{Y/X} := K_Y - \mu^* K_X$.
In his book Positivity in Algebraic Geometry II, Lazarsfeld mentions in passing (pg.146) that $\mu_* \mathcal{O}_Y(K_{Y/X})  = \mathcal{O}_X$. Why is this true?


text:
Q: oracle - regex to find parts of a version number I have a field in a table for software-style version numbers, i.e., one to three numeric values separated by "dots" but these are not decimal numbers.  For example the version after 3.9 might be 3.10, then 3.11, etc.  I'm trying to build a query to find the different parts of the version number (major version, minor version, and build#), using REGEX_SUBSTR in Oracle:
SELECT version,
    to_number(regexp_substr(version, '[^.]+', 1)) major,
    to_number(regexp_substr(version, '[^.]+', 2)) minor,
    to_number(regexp_substr(version, '[^.]+', 3)) build
FROM mytable

However, I'm getting some weird behavior which tells me I don't have the regex quite right.  For example, if my version number has two or three single-digit parts, the second digit comes up as both the "minor" and "build" numbers.  Here are some samples of the results
"3" -> 3/null/null  (the intended behavior)
"3.0" -> 3/0/0
"3.0.1" -> 3/0/0
"33.0" -> 33/3/0

How can I change the regex (or the whole query) to more easily get the parts correctly, and nulls for parts that aren't present?
FYI, I adapted these expressions from this old question about sorting by version numbers: Find the greatest version

A: You're missing an argument to regexp_substr(); you're supplying the starting position for each search, not the occurrence you want to match.
At the moment it's doing:

*

*major: start at the first character, find any non-period characters.

*minor: start at the second character, find any non-period characters.

*build: start at the third character, find any non-period characters.

which means for your values:

*

*"3" - major starts at "3" and stops, and finds nothing for minor/build.

*"3.0" - major starts at "3" and stops at the first period; minor starts at the second character, so ".0", skips the period because it has to find at least one non-period so moves on to the zero, and stops at the end; build starts at the third character, so "0", and stops at the end.

*"3.0.1" - major starts at "3" and stops at the first period; minor starts at the second character, so ".0", skips the first period because it has to find at least one non-period so moves on to the zero, and stops at the second period; build starts at the third character, so "0", and also stops at second period.

*"33.3" - major starts at first "3" and stops at the first period, giving 33; minor starts at the second character, so the second "3", and stops at the first period; build starts at the third character, so ".0", skips the period because it has to find at least one non-period so moves on to the zero, and stops at the end, giving 0.

You need to supply both of those arguments:
SELECT version,
    to_number(regexp_substr(version, '[^.]+', 1, 1)) major,
    to_number(regexp_substr(version, '[^.]+', 1, 2)) minor,
    to_number(regexp_substr(version, '[^.]+', 1, 3)) build
FROM mytable

VERSION
MAJOR
MINOR
BUILD

3
3
null
null

3.0
3
0
null

3.0.1
3
0
1

33.0
33
0
null

fiddle


text:
Q: Android Create Video Thumbnail at specific time I already got it to create a thumbnail from my video.
The code looks like this:
videoGalleryThumbnails.add(ThumbnailUtils.extractThumbnail(ThumbnailUtils.createVideoThumbnail(
                    videoFile.getAbsolutePath(), MediaStore.Images.Thumbnails.MINI_KIND), 500, 200));

But the thumbnail created is at a really bad time. It is exactly when the video is black. Now i have no use of a completely black Thumbnail.
How can i take a Thumbnail of my video at a specific time? E.g. at 00:31 or at 01:44?
Or is it not possible?
I tried also to use MediaMetadataRetriever, but i get only a white image. Code looks like this
File tempVideoList[] = (Environment.getExternalStoragePublicDirectory(PATH_VIDEO_GALLERY))
            .listFiles();
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Bitmap myBitmap=null;
for (File videoFile : tempVideoList) {
    if (videoFile.isFile()) {
        //from here
        try {
            retriever.setDataSource(videoFile.getAbsolutePath());
            myBitmap = retriever.getFrameAtTime(11); //at 11th second
        } catch (Exception ex) {
            Log.i("MyDebugCode", "MediaMetadataRetriever got exception:" + ex);
        }

    videoGalleryThumbnails.add(myBitmap);
    //to here
}

If i replace the code marked as "from here" to "to here" with the top first code, it works.
I also tried MediaMetadataRetriever.OPTION_CLOSEST and OPTION_CLOSEST_SYNC and OPTION_NEXT_SYNC.

A: Ok i got it.
The MediaMetadataRetriever was absolutely the right way to go. The problem is, that it counts the time in microseconds and not in seconds. Solution looks like this:
try {
        retriever.setDataSource(videoFile.getAbsolutePath());
        int timeInSeconds = 30;
        myBitmap = retriever.getFrameAtTime(timeInSeconds * 1000000,
                    MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
    } catch (Exception ex) {
        Log.i("MyDebugCode", "MediaMetadataRetriever got exception:" + ex);
    }

videoGalleryThumbnails.add(myBitmap);

I don't know, if OPTION_CLOSEST_SYNC is actually needed, but it looks like this is the better way for programming.
Thanks to William Riley for pointing me in the right direction.

A: need little changes for this code:
try {

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

//have to control the version for the setDataSource
   if (Build.VERSION.SDK_INT >= 14)
       retriever.setDataSource(video_path, new HashMap<String, String>());
   else
       retriever.setDataSource(video_path);
   int timeInSeconds = 5;
   Bitmap thumb = retriever.getFrameAtTime(timeInSeconds * 1000000,
                                MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
   imageViewThumb.setImageBitmap(thumb);
   } catch (Exception ex) {
        ex.printStackTrace();
   }

if we don't control the version for "setDataSource" then we will get exceptions. for me it was not working until version controlling.