text:
Q: Disappearing Rails Controller Rails keeps losing reference one of my controllers. If I restart the server, it will return, then after a bit of navigating, I'll get the uninitalized constant Controller error again...
I've never seen this error before.
Here's a dump of the rake:
admin_teams GET       /admin/teams(.:format)               admin/teams#index
POST                  /admin/teams(.:format)               admin/teams#create
new_admin_team GET    /admin/teams/new(.:format)           admin/teams#new
edit_admin_team GET   /admin/teams/:id/edit(.:format)      admin/teams#edit
admin_team GET        /admin/teams/:id(.:format)           admin/teams#show
PATCH                 /admin/teams/:id(.:format)           admin/teams#update
PUT                   /admin/teams/:id(.:format)           admin/teams#update
DELETE                /admin/teams/:id(.:format)           admin/teams#destroy

Here's the routes:
namespace :admin do
  resources :team_members
  resources :organizations
  resources :users
  resources :teams
end

the controller:
module Admin
  class TeamsController < Admin::AdminController
    def index
      @teams = Team.all
    end
  end
end

the views:

** Update **
Here's the log trace:
ActionController::RoutingError - uninitialized constant Admin::TeamsController:
  activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:270:in `const_get'
  activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:270:in `block in constantize'
  activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:266:in `each'
  activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:266:in `inject'
  activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:266:in `constantize'
  actionpack (5.0.0.1) lib/action_dispatch/http/request.rb:93:in `controller_class'
  actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:44:in `controller'
  actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:30:in `serve'
  actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:39:in `block in serve'
  actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `each'
  actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `serve'
  actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:725:in `call'
  warden (1.2.6) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.6) lib/warden/manager.rb:34:in `catch'
  warden (1.2.6) lib/warden/manager.rb:34:in `call'
  rack (2.0.1) lib/rack/etag.rb:25:in `call'
  rack (2.0.1) lib/rack/conditional_get.rb:25:in `call'
  rack (2.0.1) lib/rack/head.rb:12:in `call'
  rack (2.0.1) lib/rack/session/abstract/id.rb:222:in `context'
  rack (2.0.1) lib/rack/session/abstract/id.rb:216:in `call'
  actionpack (5.0.0.1) lib/action_dispatch/middleware/cookies.rb:613:in `call'
  actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call'
  activesupport (5.0.0.1) lib/active_support/callbacks.rb:97:in `__run_callbacks__'
  activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_call_callbacks'
  activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks'
  actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:36:in `call'
  actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
  actionpack (5.0.0.1) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
  airbrake (6.0.0) lib/airbrake/rack/middleware.rb:52:in `call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'
  actionpack (5.0.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call'
  web-console (3.4.0) lib/web_console/middleware.rb:135:in `call_app'
  web-console (3.4.0) lib/web_console/middleware.rb:28:in `block in call'
  web-console (3.4.0) lib/web_console/middleware.rb:18:in `catch'
  web-console (3.4.0) lib/web_console/middleware.rb:18:in `call'
  actionpack (5.0.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
  railties (5.0.0.1) lib/rails/rack/logger.rb:36:in `call_app'
  railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `block in call'
  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `block in tagged'
  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `tagged'
  railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `call'
  actionpack (5.0.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call'
  rack (2.0.1) lib/rack/method_override.rb:22:in `call'
  rack (2.0.1) lib/rack/runtime.rb:22:in `call'
  activesupport (5.0.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
  actionpack (5.0.0.1) lib/action_dispatch/middleware/static.rb:136:in `call'
  rack (2.0.1) lib/rack/sendfile.rb:111:in `call'
  railties (5.0.0.1) lib/rails/engine.rb:522:in `call'
  puma (3.6.2) lib/puma/configuration.rb:225:in `call'
  puma (3.6.2) lib/puma/server.rb:578:in `handle_request'
  puma (3.6.2) lib/puma/server.rb:415:in `process_client'
  puma (3.6.2) lib/puma/server.rb:275:in `block in run'
  puma (3.6.2) lib/puma/thread_pool.rb:116:in `block in spawn_thread'


text:
Q: How to get a Spring XD Module metadata from within the module itself I created a Spring XD module that needs to have access to its ModuleMedatada.
I can get metadata through ZooKeeperModuleMetadataRepository but I'm yet to find out how can I uniquely identify my running module.
Given the sample module:
@MessageEndpoint
public class DummyAugmenter {

    @Transformer(inputChannel = "input", outputChannel = "output")
    public Message<?> augmentMessage(Message<?> originalMessage) throws IOException {
        // Get module metada
        System.out.println("I am associated with stream " +
                                metadata.getUnitName() +
                                " and my instance number is " +
                                metadata.getId().getIndex());
        // Some logic
        return newMsg;
    }
}

In the plugin documentation it is emphasised that a module has its own context, however it is unclear how to get that context (if possible) and what information it holds.
Any help would be much appreciated!

A: It turns out that the module metadata information is provided through the properties sources. You can get them through:
    @Value("${xd.module.name}")
    private String moduleName;

    @Value("${xd.module.sequence}")
    private String moduleIdx;

    @Value("${xd.container.id}")
    private String containerId;

    @Value("${xd.stream.name}")
    private String streamName;

    // ...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Permissions for apache webroot folder on dev server? I am a web developer and have Apache setup on my local system for testing.
I keep running into issues with the permissions e.g. unless I chmod any new directories to 777 my IDE cannot write to the files there.
I was hoping there was a way to add myself to the group that has control of the www folder (and any sub folders) so I do not have to chmod the files every time.

A: I am working on a related issue, but in your case, you could just add yourself to the web group
sudo adduser $USER www-data

replace USER$ with your username of course.
www-data is the group used for apache web access.

A: don't use 777 just because it "works". You can use easier notation such as u+rwx in order to give the user the right permission. g for group, u for "user" and o for "others". chmod ugo+rwx is then equal to 777; anyone can do anything with any files or directory. Usually not what you want.
You may want to use setgid on the directory using chmod g+s. This way, when someone changes a file, the group ownership will stay the same. Also, when you create new files and directories, this will be inherited.

A: If you use an desktop environment, you can do this.
Open the terminal and enter:
gksudo nautilus

Enter your password and hit Enter. Navigate to the www folder and right-click. Choose properties and afterwards permission. Now you can change the access.
To quit Nautilus, just close it and to close the terminal, idem.

A: You could do this, if you just want to add your user:
sudo chgrp -R yourusername /var/www
sudo find /var/www -type d -exec chmod g=rwxs {} \;
sudo find /var/www -type f -exec chmod g=rws {} \;

Replace yourusername with the actual user name that you want to add. One last thing, you can keep adding user names by repeating the command, only putting their user name.
Hope this helps!
Source


text:
Q: luajit qsort callback example memory leak I have the following qsort example to try out callbacks in luajit. However it has a memory leak (luajit: not enough memory when executing) which is not obvious to me.
Can somebody give me some hints on how to create a proper callback example?
local ffi = require("ffi")

-- ===============================================================================

ffi.cdef[[
    void qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *));
]]

function compare(a, b)
    return a[0] - b[0]
end

-- ===============================================================================

-- Explicitly convert to a callback via cast
local callback = ffi.cast("int (*)(const char *, const char *)", compare)

local data     = "efghabcd"
local size     = 8
local loopSize = 1000 * 1000 * 100.

local bytes    = ffi.new("char[15]")

-- ===============================================================================

for i=1,loopSize do
    ffi.copy(bytes, data, size)
    ffi.C.qsort(bytes, size, 1, callback)
end

Platform: OSX 10.8
luajit: 2.0.1

A: The problem appears to be that lua never gets a chance to perform a full garbage collection cycle inside the tight loop. As hinted by the comment, you can correct this by calling collectgarbage() yourself inside the loop.
Note that calling collectgarbage() on every iteration will impact the running time of whatever you're benching. To minimize this, you should set a threshold to limit how often collectgarbage() gets called:
local memthreshold = 2 ^ 20 / 1024
local start = os.clock()
for i = 1, loopSize do
    ffi.copy(bytes, data, size)
    ffi.C.qsort(bytes, size, 1, callback)
    if collectgarbage'count' > memthreshold then
      collectgarbage()
    end
end
local elapse = os.clock() - start
print("elapsed:", elapse..'s')


text:
Q: SQL Select Data Retrieval with Local Variables I'm trying to write an SQL statement that has some cascading conditional logic in it.  I have several fields that need to be returned but their values are conditional on previously determined fields.  For example, buysell_flag is dependent on the spotfwd_flag value and counter_amt and given_amt are dependent on the buysell_flag value, and so on.
I found out quickly that I cannot combine a data retrieval query and a variable assigning query in the same space, so I tried all sorts of things but couldn't return the data I wanted to.  This is a template for clients, who will be editing this SQL and pasting it into a program.  It will not always be the same, so I can't handle the logic in the program or in a stored proc or UDF.  I've tried to use a table, but when inserting that and selecting stuff to it, I ran into the same problems.  You can see my attempts below, but if it can't be done, please let me know - otherwise, I'm open to any and all suggestions!  Thanks!
    DECLARE @trans_type nvarchar(255), @trade_date nvarchar(255), @settle_date nvarchar(255),
@order_id nvarchar(255), @oaexecbroker nvarchar(255), @exec_broker nvarchar(255),
@ostatus nvarchar(255), @trade_id nvarchar(255), @reference_price nvarchar(255),
@given_ccy nvarchar(255), @spotfwd_flag nvarchar(255), @buysell_flag nvarchar(255),
@counter_ccy nvarchar(255), @counter_amt nvarchar(255), @given_amt nvarchar(255),
@oacct_cd nvarchar(255)

SELECT
@trans_type = o.trans_type,
@settle_date = o.settle_date,
@order_id = o.order_id,
@oaexecbroker = oa.exec_broker,
@exec_broker = o.exec_broker,
@ostatus = o.status,
@trade_id = oa.trade_id,
@reference_price = o.exec_price,
@given_ccy = o.target_crrncy,

--o.trans_type    AS trans_type,
--  o.trade_date    AS trade_date,
--  o.settle_date   AS settle_date,
--  o.order_id      AS order_id,
--  oa.exec_broker  AS oaexecbroker,
--  o.exec_broker   AS exec_broker,
--  o.status        AS ostatus,
--  oa.trade_id     AS trade_id,
--  o.exec_price    AS reference_price,
--  o.target_crrncy as given_ccy,
    -- for spot/fwd

    @spotfwd_flag = CASE
        WHEN LEFT(o.inv_class_cd,1) = 'F' THEN ('FWD')
        WHEN LEFT(o.inv_class_cd,2) = 'CU' THEN ('SPOT')
    ELSE 'SPOT'
    END, -- must be spot or fwd
    --for buysell

    @buysell_flag = CASE
        WHEN @spotfwd_flag = 'FWD' THEN
            CASE
                WHEN o.target_crrncy = o.to_crrncy THEN 'BUY'
                ELSE 'SELL'
            END
    ELSE
        CASE
            WHEN o.trans_type = 'BUYL' THEN 'BUY'
            ELSE 'SELL'
        END
    END, -- must be buy or sell

    @counter_amt = CASE
        WHEN @buysell_flag = 'BUY' Then oa.exec_amt
        ELSE oa.exec_qty
    END,

    @given_amt = CASE
        WHEN @buysell_flag = 'SELL' THEN oa.exec_amt
        ELSE oa.exec_qty
    END,

    @counter_ccy = CASE
        WHEN o.target_crrncy = o.to_crrncy THEN o.from_crrncy
        ELSE o.to_crrncy
    END,

    @oacct_cd = CASE
        WHEN f.udf_char6 = 'Y' THEN (oa.acct_cd + oa.custodian)
        ELSE oa.acct_cd
    END
FROM   ts_order_alloc oa
    LEFT OUTER JOIN ts_order o
    ON oa.order_id = o.order_id
    LEFT OUTER JOIN cs_fund f
    ON oa.acct_cd = f.acct_cd
--  LEFT OUTER JOIN csm_security s
--  ON o.sec_id = s.sec_id
--WHERE  s.sec_typ_cd IN ( 'CFWD', 'CURR' )
--  AND o.status IN ( 'READY','ACCT' )
--  AND oa.usr_class_cd_2 = 'GTSSREADY'

select @trans_type as trans_type,
    @trade_date    AS trade_date,
    @settle_date   AS settle_date,
    @order_id      AS order_id,
    @oaexecbroker  AS oaexecbroker,
    @exec_broker   AS exec_broker,
    @ostatus        AS ostatus,
    @trade_id     AS trade_id,
    @reference_price   AS reference_price,
    @given_ccy as given_ccy,
    @buysell_flag as buysell_flag,
    @spotfwd_flag as spotfwd_flag,
    @given_ccy as given_ccy,
    @counter_ccy as counter_ccy,
    @given_amt as given_amt,
    @counter_amt as counter_amt

EDIT:
I'm expecting to get rows out based on the given variables.  The reason I have so many vars is I was trying to get make it comply to the SQL error messages.
Should come out like so:
trans_type  trade_date  settle_date order_id    oaexecbroker    exec_broker ostatus trade_id    reference_price given_ccy   buysell_flag    spotfwd_flag    given_ccy   counter_ccy given_amt   counter_amt
BUYL    NULL    2010-04-06 00:00:00.000 1442084139  3PCITI  3PCITI  Ready   1389278710  1.50705 GBP BUY SPOT    GBP USD 604292  910699

A: If I'm understanding this problem correctly, what you need to do is encapsulate the logic of the calculations to use the results of those calculations later on.
Depending on the inputs of the calculations, there are many different ways of going about doing this.

*

*If the logic only involves values within a single row in a single table, you could define a computed column to encapsulate the logic. How this works is when you SELECT the value of the computed column, the calculation is done automatically. This method is suitable when you need to reuse the same logic very frequently, as this is a permanent change to the table structure.

*A great way to encapsulate logic is within a view. This is kind of like a persisted column, except the results could combine data from multiple tables. Since a view can only encompass a single SELECT statement, you can combine it with any of the other methods presented here.

*Derived tables. That sounds fancy, but the concept is very simple: use the results of a SELECT statement as the input of another SELECT statement. Take the following example:
DECLARE @test table
(
    Col1 int,
    Col2 int
);

-- Result query (2)
SELECT
    a.Col1,
    (
        CASE
            WHEN a.Col3 < a.Col1 THEN 1  -- Use the computation
            ELSE 5
        END
    ) AS Col4
    FROM
    (
        -- Derived table (1)
        SELECT
            Col1,
            Col2 + Col1 AS Col3  -- Compute
            FROM @test t1
    ) a;

The innermost query happens first (1), and in the outer query (2), you can use the results of the inner query. Continue nesting until there are no more "layers" to the computation.

*Common table expressions (CTEs). This is similar to derived tables, but a slightly different syntax, and they give you the ability to reuse the logic multiple times in the main query. Essentially, a CTE is like a view that only exists for a single query. Here is the same example as above, using a CTE instead of a derived table:
DECLARE @test table
(
    Col1 int,
    Col2 int
);

WITH a AS
(
    -- CTE (1)
    SELECT
        Col1,
        Col2 + Col1 AS Col3  -- Compute
        FROM @test t1
)
    -- Result query (2)
    SELECT
        a.Col1,
        (
            CASE
                WHEN a.Col3 < a.Col1 THEN 1  -- Use the computation
                ELSE 5
            END
        ) AS Col4
        FROM a;

For the query you posted, you'll need more than 2 layers, so you may need to combine some of these methods, or just used derived tables for everything. The main thing is that after applying these methods, you'll probably find there's no need to use any scalar variables!


text:
Q: How can i access my custom webpart in sharepoint foundation 2010? So i just started trying to develop a simple webpart today for a sharepoint foundation i put on a virtual machine. I have no previous experience with sharepoint whatsoever.
As i cant run a sharepoint 2010 on my local machine for dev purposes i followed advices in this thread http://social.technet.microsoft.com/Forums/en/sharepoint2010programming/thread/cda807f6-4edf-4efc-8e9b-4d446356c8ae to able to actually develop something (just the registry bit).
I created the simple test web part (writes out "hi"), uploaded it to virtual machine, added it with add-spsolution and install-spsolution in powershell with success. When i do get-solution through powershell on my webpart it says deployed  = true.
What am i missing from here to get it to actually show up somewhere in the web interface so i can add it to a page?
Cheers

A: You need to go into site settings and activate the feature. If its already activated edit the page > Insert WebPart > Look under Custom to find your webpart.
HTH


text:
Q: Delete rows while keeping the one with oldest date entry using SQL (MySQL) I have a few million database rows in MySQL InnoDB database which need to get cleaned up. Look at this example.
SELECT archiveid, clearingid, pickdate
  FROM tblclearingarchive
  WHERE clearingid = 30978729
  ORDER BY pickdate;

+-----------+------------+---------------------+
| archiveid | clearingid | pickdate            |
+-----------+------------+---------------------+
|  34328367 |   30978729 | NULL                | *
|  34333844 |   30978729 | 2015-10-27 15:55:30 | <- keep only this row with oldest date
|  34438038 |   30978729 | 2016-03-01 10:34:25 | *
|  34481472 |   30978729 | 2016-04-20 13:44:19 | *
+-----------+------------+---------------------+
4 rows in set (0.01 sec)

So I know the clearingid value(s) of the affected field(s) and want to remove the one with no pickdate (null) and the two lines which are redundant (later, after first pick). In the example above, the ones marked with * should get deleted.
Any hints about how such SQL update/delete might look like?
There are about 30M rows and about 250K rows (known clearingid's) to clean up.
With the initial idea of Matias Barrios I found this solution to verify. It perfectly lists the rows I want to delete:
SELECT archiveid, clearingid, pickdate
  FROM tblclearingarchive
  WHERE clearingid = 30978729
  AND (pickdate NOT IN (SELECT MIN(pickdate)
                        FROM tblclearingarchive
                        WHERE clearingid = 30978729 )
       OR pickdate is NULL)
  ORDER BY pickdate;

+-----------+------------+---------------------+
| archiveid | clearingid | pickdate            |
+-----------+------------+---------------------+
|  34328367 |   30978729 | NULL                |
|  34438038 |   30978729 | 2016-03-01 10:34:25 |
|  34481472 |   30978729 | 2016-04-20 13:44:19 |
+-----------+------------+---------------------+
3 rows in set (0.20 sec)

But I fail to delete using this sort of query:
DELETE FROM tblclearingarchive
  WHERE clearingid = 30978729
  AND (pickdate NOT IN (SELECT MIN(pickdate)
                        FROM tblclearingarchive
                        WHERE clearingid = 30978729 )
      OR pickdate is NULL);

ERROR 1093 (HY000): You can't specify target table 'tblclearingarchive' for update in FROM clause

A: You will need to do this:
Create "assistance table" so you can do the delete
create table test as
select * from tblclearingarchive

Then do the delete:
delete from tblclearingarchive t1
where t1.pickdate <> (select min(t.pickdate)
                     from test t
                     group by clearingid)
or t1.pickdate is null;

Here is a small demo

A: If you want the first, then you can filter:
select t.*
from t
where t.pickdate = (select min(t2.pickdate)
                    from t t2
                    where t2.clearingid = t.clearingid
                   );

Or, if you just want one row:
select t.*
from t
where t.pickdate is not null
order by t.pickdate
limit 1;

EDIT:
If you want to actually modify the table:
delete t
    from t join
         (select clearingid, min(pickdate) as min_pickdate
          from t
          group by clearingid
         ) c
         on t.clearingid = c.clearingid
    where t.pickdate > c.min_pickdate or t.pickdate is null;

A: This should do as you intend.
DELETE FROM tblclearingarchive
  WHERE archiveid IN (
    SELECT * FROM ( SELECT archiveid, clearingid, pickdate
      FROM tblclearingarchive
      WHERE clearingid = 30978729
      AND pickdate NOT IN ( SELECT max(pickdate)
                        FROM tblclearingarchive LIMIT 1)
      ORDER BY pickdate) tmpTable
   ) OR  pickdate IS NULL

Let me know if it works.


text:
Q: In Android how to decode a jpeg in cmyk color format? I'm trying to decode a jpeg that is in CMYK color format. BitmapFactory returns null. I googled around but with no luck. Is it possibile Android team did not the right job supporting all kind of color format?
I'm using Android 2.2.
Thank you so much.

A: Found the solution: loading the JPEG using the external library libjpeg compiled with NDK. It has been a hard work, but I did it!

A: It's very possible I'd say:
http://code.google.com/p/skia/issues/detail?id=69


text:
Q: matlab sphere definition as txt file I wrote a matlab file to generate a 3D sphere:
obstacle.origin_x=1.6;
obstacle.origin_y=0.8;
obstacle.origin_z=0.2;
obstacle.radius_obs=0.2;
save('obstacle.mat', 'obstacle');

I found a code which is appropriate for my problem but the obstacle definition is in .txt format
how can I define it as a .txt format?
For instance in the code that I found, a rectangular prism is defined as:
-0.5000         0    0.5000
0.1500         0    0.5000
0.1500         0   -0.5000
-0.5000         0   -0.5000

0.3500         0    0.5000
0.5000         0    0.5000
0.5000         0   -0.5000
0.3500         0   -0.5000

0.1500         0    0.5000
0.3500         0    0.5000
0.3500         0    0.3500
0.1500         0    0.3500

0.1500         0    0.1500
0.3500         0    0.1500
0.3500         0   -0.5000
0.1500         0   -0.5000

A: It's hard to understand your question... this is what I interpret:
you want to define the raster points of a sphere (= "obstacle") in a txt-file, instead of defining only the parameters of the sphere within a struct?
If this is true you at first have to calculate all the raster points of the sphere by yourself, and then you can print them to a text file, e.g. using fprintf.
I've written a short function which draws a sphere:
function drawsphere()

bound_horz = 360*pi/180;    % horizontal angle boundaries
bound_vert = 90*pi/180;     % vertical angle boundaries
stepsize = 30;              % discretization step size
r = 400;                    % radius of sphere

% define angle raster points
[theta,phi] = meshgrid(linspace(-bound_horz,bound_horz,stepsize),linspace(-bound_vert,bound_vert,stepsize));
% convert them to Cartesian coordinates
x = r.*cos(theta).*cos(phi);
y = r.*sin(theta).*cos(phi);
z = r.*sin(phi);

C1 = zeros(size(x));
C2 = zeros(size(x));
C3 = ones(size(x));
col = cat(3,C1,C2,C3);

% draw the sphere
fig333=figure(333);clf
cameratoolbar(fig333,'Show')
cameratoolbar(fig333,'SetMode','orbit')
axis vis3d
surf(x,y,z,col);

Add fprintf-calls in the end to write x/y/z to a .txt file.


text:
Q: How to access button in different listview rows? I'm trying to change the color of buttons in the rows of listview by clicking a button. Here I've a listview composed of 25 rows and each rows contains a button. I've used custom adapter for listview to place button in each row. I like to know how to do following things:

*

*Click on a button and its color is changed.

*After step (1) the onClickListener also change the color of the left-over buttons in the listview to normal.

*The above two steps should happen to all of the buttons means if any of the button is clicked then it should be colored and remaining will turn back to normal.

the listview is like

        Button 1

        Button 2

        Button 3

        Button 4

A: You have to access your Button from Adapter. Follow it -
public class TestAdapter extends BaseAdapter {
    private Context ctx;
    private List<TestList> list;

    public TestAdapter(Context ctx, List<TestList> list){
        this.ctx = ctx;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public TestList getItem(int position) {

        return list.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.layout_item, parent, false);
        }

        Button button = (Button) convertView.findViewById(R.id.button);

        button.setText(list.get(position));

        return  convertView;
    }
}

A: Use onclick listener for button in your custom adapter
public class CustomAdapter extends BaseAdapter {
    private Context ctx;
    private List<CustomList> list;

    public CustomAdapter(Context ctx, List<CustomList> list){
        this.ctx = ctx;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public CustomList getItem(int position) {

        return list.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.layout_item, parent, false);
        }

        Button button = (Button) convertView.findViewById(R.id.button);

        button.setText(list.get(position));

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                \\change color here
            }
        });

        return  convertView;
        }
    }


text:
Q: minikube and how to debug api server error I dont get what is going on with minikube.  Below are the steps I undertook to fix the problem with a stopped apiserver.
1) I dont know why the api server stopped. How do I debug? this folder is empty:
 --> EMPTY ~/.minikube/logs/

2) After stop I start again and minikube says all is well.  I do a status check and I get apiserver: Error.  So...no logs..how do I debug?
3) And finally what would cause and apiserver error?
Thanks
~$ minikube status
host: Running
kubelet: Running
apiserver: Stopped
kubectl: Correctly Configured: pointing to minikube-vm at 192.168.99.100~$

~$ minikube stop
Stopping local Kubernetes cluster...
Machine stopped.
~$ minikube start
Starting local Kubernetes v1.12.4 cluster...
Starting VM...
Getting VM IP address...
Moving files into cluster...
Setting up certs...
Connecting to cluster...
Setting up kubeconfig...
Stopping extra container runtimes...
Machine exists, restarting cluster components...
Verifying kubelet health ...
Verifying apiserver health .....Kubectl is now configured to use the cluster.
Loading cached images from config file.

Everything looks great. Please enjoy minikube!

~$ minikube status
host: Running
kubelet: Running
apiserver: Error


text:
Q: Taxonomy Column Values not fetching from Code after batch deleting and adding them again I have a SharePoint 2013 site with custom lists containing taxonomy columns. It had data initially. But for some requirement, I had to do a batch delete of those list items and repopulate them through an application. I also cleanup the TaxonomyHiddenList using batch delete and also remove the terms from the term store except the termsets, since the terms get dynamically created from an application. The re-population happens properly after I re-add the items and I can see them through the UI also. But when I try to read the taxonomy column values again from code after executing a CAML query, it is not throwing any exception, but at the same time, fetching blank values. I mean the taxonomy column returns 0 as count, though there is a value. Has anyone faced this issue before? If so, can you please help? This is a critical issue, blocking us from going live. So, please help ASAP.

A: Update your code to get taxonomy column value:
TaxonomyFieldValueCollection spTaxonomyFiledValueCollection = spListItem[taxonomyField] as TaxonomyFieldValueCollection;

          foreach (var field in spTaxonomyFiledValueCollection)
          {
              fieldValue = field.Label;
          }


text:
Q: Android: Set margin to left side of radiobutton drawable I want to set a margin / padding between my radiobutton drawable and the left side of it, e.g: Setting a margin of 8dp between my radiobutton drawable and the left side of the screen. I know how to set a margin between the radiobutton itself, but not how to do it with the radiobutton drawable. I also know how to set a margin right side of the radiobutton drawable with paddngStart="YOUR_PADDING".
Is this possible?
Here a picture of what I mean:
Currently

What I want

EDIT
The aboven written answer does work. For those wo want to set the value inside the layout and not programmatically, I have written a binding adapter:
@BindingAdapter("setDrawableLeftPadding")
fun setDrawableLeftPadding(view: CustomRadioButton, padding: Float) {
    view.setStartPaddingDp(padding)
}

You can then use it inside your CustomRadioButton layout with app:setDrawableLeftPadding="@{8f}"

A: I you want to achieve the exact same on what your second picture shows, you can write a custom RadioButton that handle this padding, the custom view code can be like this (in Kotlin):
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatRadioButton

class CustomRadioButton : AppCompatRadioButton {

    // the value of your padding (in pixels) from the start of the radio button
    var startPadding: Int = 0
        get
        set(value) {
            field = value
            requestLayout()
        }

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    fun setStartPaddingDp(paddingDp: Float) {
        startPaddingPx = (paddingDp * context.resources.displayMetrics.density).toInt()
    }

    override fun onDraw(canvas: Canvas?) {
        // todo: handle Right-To-Left layouts
        canvas?.translate(startPadding.toFloat(), 0f)

        super.onDraw(canvas)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        setMeasuredDimension(measuredWidth + startPadding, measuredHeight)
    }
}

You can set the padding value by setting the value of the field startPadding, for example:
yourCustomRadioButton.startPadding = 100 // this value is in pixels

// or

yourCustomRadioButton.setStartPaddingDp(100) // this value is in DP

A: val compoundButtonDrawable = CompoundButtonCompat.getButtonDrawable(radioButton)
val insetDrawable = InsetDrawable(compoundButtonDrawable, 32, 0, 0, 0)
radioButton.buttonDrawable = insetDrawable


text:
Q: Error when importing .CSV file into DataGrid I am trying to get data from .CSV file into DataGrid in a WPF application.
Here is my code. The problem is that when I click on the button and select the file, the code throws an exception "Syntax error in PropertyPath 'Unmatched parenthesis ".
What is wrong in this code ?
    private void OnImport(object sender, RoutedEventArgs e)
    {
       try
        {
            lFnLoadFileData();
        }
        catch (Exception)
        {
            throw;
        }
    }

    void lFnLoadFileData()
    {
        try
        {
            Microsoft.Win32.OpenFileDialog lObjFileDlge = new Microsoft.Win32.OpenFileDialog();
            lObjFileDlge.Filter = "CSV Files|*.xlsx";
            lObjFileDlge.FilterIndex = 1;
            lObjFileDlge.Multiselect = false;
            string fName = "";
            bool? lBlnUserclicked = lObjFileDlge.ShowDialog();
            if (lBlnUserclicked != null || lBlnUserclicked == true)
            {
                fName = lObjFileDlge.FileName;
            }
            if (System.IO.File.Exists(fName) == true)
            {
                // FileStream lObjFileStream = lObjFileDlge.File.OpenRead();
                StreamReader lObjStreamReader = new StreamReader(fName);
                System.Windows.MessageBox.Show(lObjStreamReader.ToString());
                lFnGenerateData(lObjStreamReader);
                lObjStreamReader.Close();
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    void lFnGenerateData(StreamReader aReader)
    {
        try
        {
            bool lBlnIsColumns = true;
            string[] lArrCols = null;
            List<Contacts> lstPersonalList = new List<Contacts>();
            dataGrid1.Columns.Clear();
            while (aReader.Peek() > 0)
            {
                string lStrLine = aReader.ReadLine();
                if (lStrLine == null)
                    break;
                if (lStrLine.Trim() == "")
                    continue;
                string[] lArrStrCells = null;
                lArrStrCells = lStrLine.Split(';');
                if (lArrStrCells == null)
                    continue;
                if (lBlnIsColumns)
                {
                    lArrCols = lArrStrCells;
                    foreach (string lStrCell in lArrStrCells)
                    {
                        DataGridTextColumn lDGCol = new DataGridTextColumn();
                        lDGCol.Header = lStrCell;
                        lDGCol.Binding = new System.Windows.Data.Binding(lStrCell);
                        dataGrid1.Columns.Add(lDGCol);
                    }
                    lBlnIsColumns = false;
                    continue;
                }
                if (lArrCols == null)
                    continue;

                int lIntColID = 0;
                Contacts objPersonalInfo = new Contacts();
                objPersonalInfo.ContactName = lArrStrCells[0];
                objPersonalInfo.ContactNumber = lArrStrCells[1];
                objPersonalInfo.Status  = lArrStrCells[2];

                lstPersonalList.Add(objPersonalInfo);
            }
            aReader.Close();
            dataGrid1.ItemsSource = lstPersonalList;

        }
        catch (Exception)
        {
            throw;
        }
    }

A: I think the problem is likely caused by this line. You are trying to bind to an invalid property name?
lDGCol.Binding = new System.Windows.Data.Binding(lStrCell);


text:
Q: How to build a Slide-Up Menu in Xcode I'm new to Xcode development, and I'd like to develop a slide-up menu triggered from a UIToolbar in my iPhone app.
What I'm looking at is creating a subview with menu buttons, adding it to the main view, and sliding it up(visible) or down(hidden) when the toggle button is tapped.
How do I do this programmatically?! The Opera app for iPhone does this well (see the picture).

A: What you are saying can be done by code by adding a subview to your mainview and slide it up and down to make it visible and unvisible.
1) Add a subview to far y coordinate so that initially its not visible in the view.
subView  =  [[UIView alloc]initWithFrame:CGRectMake(0,470,320,200)]]; // subView is an ivar
// Add stuffs to your subview
[self.view addSubview:subView];

2) Now make two IBActions showMySubview and hideMySubview and link them to the corresponding buttons or you can do some toggling with one button by checking its label.text.
3)    In your showMySubview
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:1.5];
        [UIView setAnimationDelay:0.0];
        subView.frame = CGRectMake(0, 50, 320, 200);
        [UIView commitAnimations];

4) In your hideMySubview
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:1.5];
        [UIView setAnimationDelay:0.0];
        editPopUpView.frame = CGRectMake(0, 470, 320, 200);
        [UIView commitAnimations];

You can also do some beautify things to your subview to look some good add QuartzCore framework to your project and import it in your .m file and add these lines after adding your subview to your mainview the import is    #import "QuartzCore/QuartzCore.h"
[[subView layer] setCornerRadius:12.0f];
[[subView layer] setMasksToBounds:YES];
[[subView layer] setBorderWidth:4.0f];
[subView layer].borderColor =   [UIColor purpleColor].CGColor;

Hope This will help you in anyways :)
EDIT :
Adding buttons via code to your subview :
for (int i = 0; i < 3; i++) {

    for (int j = 0; j < 3; j++) {

        UIButton *btn   =   [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame       =   CGRectMake(j*60,200+ 35 * i ,50 , 30);
        //[btn setTitle:@"Test" forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateHighlighted];
        btn.tag =   (j + 1) + (3 * i);
        [btn addTarget:self action:@selector(subViewButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        btn.showsTouchWhenHighlighted   =   YES;
        [subView addSubview:btn]; // its the subview we added to our main view add this after initializing the subview

    }
}

Now a function to catch the clicks of all the buttons
-(IBAction)subViewButtonClicked:(id)sender
{
    switch ([sender tag]) {
    case 1:
    {
        // Do your stuff here

         NSLog(@"the tag of sender is %i",[sender tag]);

        break;
    }

    case 2:
    {
        // Do your stuff here

         NSLog(@"the tag of sender is %i",[sender tag]);

        break;
    }
    case 3:
    {
        // Do your stuff here

         NSLog(@"the tag of sender is %i",[sender tag]);

        break;
    }
    case 4:
    {
        // Do your stuff here

         NSLog(@"the tag of sender is %i",[sender tag]);

        break;
    }
    case 5:
    {
        // Do your stuff here

         NSLog(@"the tag of sender is %i",[sender tag]);

        break;
    }

    case 6:
    {
        // Do your stuff here

         NSLog(@"the tag of sender is %i",[sender tag]);

        break;
    }
    case 7:
    {
        // Do your stuff here

         NSLog(@"the tag of sender is %i",[sender tag]);

        break;
    }
    case 8:
    {
        // Do your stuff here

         NSLog(@"the tag of sender is %i",[sender tag]);

        break;
    }

    case 9:
    {
        // Do your stuff here

         NSLog(@"the tag of sender is %i",[sender tag]);

        break;
    }
    default:
        break;
}

}

There may be many easy ways out there but hope this will get you a start :)


text:
Q: Issues with newest version (cassandra 1.15) I tried installing newest cassandra version using the tarball binary available at -
http://www.apache.org/dyn/closer.cgi?path=/cassandra/1.1.5/apache-cassandra-1.1.5-bin.tar.gz
I followed the instructions provided from the  the getting started page.
But when i run cassandra by ./cassandra -f , i get the following error#
amt@amtlt2:~/Downloads/apache-cassandra-1.1.5/bin$ ./cassandra -f
xss =  -ea -javaagent:./../lib/jamm-0.2.5.jar -XX:
+UseThreadPriorities-XX:ThreadPriorityPolicy=42 -Xms4G
Xmx4G -Xmn800M -XX:+HeapDumpOnOutOfMemoryError -Xss180k

P.S. i am installing on a server.

well i don,t have a problem with java because i am running the latest version and this version works in my other PC where cassandra is configured.

amt@amtlt2:~/Downloads/apache-cassandra-1.1.5/bin$ java -version
java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.4) (6b24-1.11.4-1ubuntu0.12.04.1)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)

and i also feel its got nothing to do with heap size because its set to very high value

# The example HEAP_NEWSIZE assumes a modern 8-core+ machine for decent pause
# times. If in doubt, and if you do not particularly want to tweak, go with
# 100 MB per physical CPU core.

MAX_HEAP_SIZE="4G"
HEAP_NEWSIZE="800M"

the interesting thing is, if i follow same instructions and download the (unsupported) cassandra 1.12 release version. It works like a gem with same configuration as i did above.

Any help really appreciated.Point out in case i am doing something wrong here.

A: You don't actually have an error being logged.  -XX:+HeapDumpOnOutOfMemoryError is actually a command-line option to the java command telling it to do a heap dump if it OOMs.


text:
Q: Identify outliers in a set of elements I have a set of elements that has been partitioned into clusters based on several criteria, one of which is the length of the elements. To be precise, element $x$ cannot belong to cluster A if $\dfrac{\operatorname{length}(x)}{\operatorname{length}(y)} < 0.65$, where $y$ is the longest element of $A$.
As I examine the clusters, there are many cases where the elements all have similar length. But occasionally I see clusters where the longest element is clearly an outlier with respect to length: the rest of the elements are all of similar length: quite a bit shorter, close to the 65% threshold. I worry that in some cases the elements are not clustering properly because the longest element is an outlier.
I would like a way to identify such problem cases. My intuition is leading me in two directions.

*

*Compute the mean length of all of the elements in the cluster except for the longest, and compare to the length of the longest.

*Compute the proportion of each element's length in the cluster to that of the longest element.

But I'm unsure where to go from there. What is an effective measure I could use to identify clusters where the longest element is an outlier with respect to length?


text:
Q: Text loads too big in small window I'm working on a site that uses jquery to change the font size on any window resize, to keep everything in the right place. It works great, but when someones browser isn't maximized, the font still loads as if it is, until the user resizes their browser. Even if I make the browser smaller than it was on page load, the font will adjust. Here is my code:
$(document).ready(function() {
    var mainwidth = $('.main').width();
    var mainheight = $('.main').height(mainwidth * .8895);
    var headerwidth = $('.header-middle').width();
    $('.main').height(mainwidth * .8895)
    $('.logo').width(headerwidth * .049);
    $('.logo').height(headerheight * .7533);
    $('.divider').width(headerwidth * .00204);
    $('.design-image').width(headerwidth * .2547);

    $('.call-us-today').css({'font-size': headerwidth * .01836});
    $('.header-paragraph').css({'font-size': headerwidth * .01734});
    $('.header-paragraph-footer').css({'font-size': headerwidth * .01632});
    $('.top-text').css({'font-size': headerwidth * .02448});
    $('.graybar-text').css({'font-size': headerwidth * .03265});
    $('.body-header').css({'font-size': headerwidth * .02245});
    $('.body-text').css({'font-size': headerwidth * .01632});
    $('.footer').css({'font-size': headerwidth * .01224});
    $('.banner-text').css({'font-size': headerwidth * .02244});

    $('.graybar-text').css({'letter-spacing': headerwidth * .00408});

});

$(window).resize(function() {
    var mainwidth = $('.main').width();
    var mainheight = $('.main').height(mainwidth * .8895);
    var headerwidth = $('.header-middle').width();
    var headerheight = $('.header-middle').height();
    $('.main').height(mainwidth * .8895);
    $('.logo').width(headerwidth * .049);
    $('.logo').height(headerheight * .7533);
    $('.lady-image').width(headerwidth * .2835);
    $('.divider').width(headerwidth * .00204);
    $('.design-image').width(headerwidth * .2547);

    $('.call-us-today').css({'font-size': headerwidth * .01836});
    $('.header-paragraph').css({'font-size': headerwidth * .01734});
    $('.header-paragraph-footer').css({'font-size': headerwidth * .01632});
    $('.top-text').css({'font-size': headerwidth * .02448});
    $('.graybar-text').css({'font-size': headerwidth * .03265});
    $('.body-header').css({'font-size': headerwidth * .02245});
    $('.body-text').css({'font-size': headerwidth * .01632});
    $('.footer').css({'font-size': headerwidth * .01224});
    $('.banner-text').css({'font-size': headerwidth * .02244});

    $('.graybar-text').css({'letter-spacing': headerwidth * .00408});
});

Does document.ready not load until after the pages loads? Any help with this would be appreciated!

A: You can do this by changing your code very slightly. Simply take the
$(window).resize(function() {

bit and change it to
$(window).resize(resizeMyStuff)

and then make a new function using your existing code that you had inside the resize handler.
function resizeMyStuff() {
var mainwidth = $('.main').width();
var mainheight = $('.main').height(mainwidth * .8895);
var headerwidth = $('.header-middle').width();
var headerheight = ... etc

That way, you can call that function at the end of your $(document).ready function therefore setting the size every time the page loads.
You can also use
var browserWidth = $(window).width();
var browserHeight = $(window).height();

to pick up your window sizes from rather than relying on a page element (that could be under the influence of some weird css inheritance or something going on).


text:
Q: Cannot find by date I am trying to get my app to pull all posts created on a specific date.
case meta_type
    when "user"
        @meta = User.find(params[:user_id])
        @meta_title = @meta.username + "'s Posts"
        @posts = Post.find(:all, :conditions => { :user_id => @meta.id})
    when "category"
        @meta = params[:category]
        @meta_title = @meta + " Posts"
        @posts = Post.find(:all, :conditions => { :category => @meta})
    when "date"
        @meta = Date.parse(params[:date])
        @meta_title = @meta.strftime("%d/%m/%Y") + " Posts"
        @posts = Post.find(:all, :conditions => { :created_at => @meta})
    end

Here is my view:
  - if @meta
        %h2= @meta_title
        - if @posts.count > 0
            - @posts.each_slice(2) do |slice|
                .row
                    - slice.each do |post|
                        .col-sm-6
                            .blog_entry
                                .img
                                %h3
                                    %a= link_to post.title, posts_path + '/' + post.id.to_s
                                = render "blog_meta", :post => post
        - else
            %p= @user.username + " has no posts."
    - else
        %h2= "User does not exist."

I am getting undefined method 'username' for nil:NilClass which in itself isn't a problem, but the fact that it is getting filtered through to the else statement is, because it should be finding posts for that date.
Also I just realised by passing through the datetime, it will actually be looking for posts created at the exact same time, whereas I would like it to pull up all posts created on the day, not the time.
Any suggestions?
Thanks

A: So, ignoring the subtleties of exactly which time zone you're evaluating the date in, you can change your when "date" block to read as follows
@meta = Date.parse(params[:date])
@meta_title = @meta.strftime("%d/%m/%Y") + " Posts"
beginning_of_day = @meta.to_datetime.beginning_of_day
end_of_day = @meta.to_datetime.end_of_day
@posts = Post.where("created_at >= ?", beginning_of_day).where("created_at < ?", end_of_day).order(:created_at).all

That will give you a list of Posts created on the day in question, in the time zone in which your app is running, ordered by creation time.
You can make a number of other adjustments (changing sort order, using a different time zone, etc.) as needed.


text:
Q: Check if null for part of session variables in PHP If I have 30 session variables and I want to do an if statement to only 10 of them.
if (empty($_SESSION['XYZ'])) {
   $_SESSION['XYZ'] = 0;
}

what should I do? Do I call an if statement after every session variables that i needed for?

A: $vars = array('XYZ','ABC','DEF');

foreach($vars as $i){
  if(empty($_SESSION[$i])) $_SESSION[$i] = 0;
}

[edit]
I like how we have the same answer 4 times now, and counting!

A: Consider putting the names of the keys  in an array and then looping through with foreach.
$keys = array('x','y','z');
foreach ($keys as $key)
{
    if (empty($_SESSION[$key])
    {
        // do stuff
    }
}

An advantage is you can quickly add or remove keys to check.

A: If they are in series, that is, from 0 to 29 then you can use a loop to traverse them!

A: Something like so?
$keys = array("A", "B", "C", "D", "E", "F");
foreach ($keys as $key) {
    if (empty($_SESSION[$key])) {
        $_SESSION[$key] = 0;
    }
}

A: You could list the keys you want to zero-out in an array and set them as follows:
$keys = array('XYZ','FOO','BAR');

foreach ($keys as $key) {
  if (empty($_SESSION[$key])) {
    $_SESSION[$key] = 0;
  }
}


text:
Q: How to constrain a generic type to a POJO? So I want to write some functions that accept a generic type T that can be any plain old javascript object, but nothing else. No class instances or functions or stuff like that. Basically, anything that could be serialized to string and then parsed back again using JSON.stringify() and JSON.parse() without losing any information.
I thought I could do that like this:
type Primitive = number|string|boolean|bigint|symbol|undefined|null

export interface PlainObject {
  [key: string]: Primitive|Primitive[]|PlainObject|PlainObject[]
}

// Let's say that this is an example
// of a more specific type that I want to use.
interface User {
  id: number
  name: string
  age: number
}

async function fetchFromApi<T extends PlainObject>(url: string): Promise<T> {
  // ...
}

Now I was hoping that I could then do this:
const user = await fetchFromApi<User>("/users/1")

But Typescript complains. And I understand the complaint. The User type is much more restrained than the PlainObject type, because User doesn't allow for just any key to be set.
But I don't know how else to express in code:

"I want this generic type T to be constrained to be a POJO, but
otherwise it may have any narrower type than that."

Can anybody tell me how I can express that in TypeScript?


text:
Q: New line is not working with files in C++? And i know that this question is already asked by some other user. Yes it is duplicated and here is the link1 and link2 . I tried every solutions given in the link but still its not working. I am using TurboC++ 4.5 compiler from borland .  And here is my code
#include<iostream.h>
#include<conio.h>
#include<fstream.h>

int main()
{
  ofstream fout;

  fout.open("COUNTRY");
  fout<<"UNITED STATES OF AMERICA \n";
  fout<<"UNITED KINGDOM \n";
  fout<<"SOUTH KOREA \n";
  fout.close();

  fout.open("CAPITAL");
  fout<<"WASHINGTON \n";
  fout<<"LONDON \n";
  fout<<"SEOUL \n";
  fout.close();

  const int N=80;
  char line[N];
  ifstream fin;

  fin.open("COUNTRY");
  cout<<"\nCONTENTS OF COUNTRY FILE\n";
  while(fin)
  {
    fin.getline(line,N);
    cout<<line;
  }
  fin.close();

  fin.open("CAPITAL");
  cout<<"\nCONTENTS OF CAPITAL FILE\n";
  while(fin)
  {
    fin.getline(line,N);
    cout<<line;
  }
  fin.close();

  return 0;
}

I checked for more solutions but can't resolve this issue and that's why i am posting it here.

A: You need to add a newline character when you write your data out. Reading it in with getline discards the "\n" at the end of each line.

If the delimiter is found, it is extracted and discarded, i.e. it is
  not stored and the next input operation will begin after it.

Here is the page that the preceding quote is from.
So the problem is that you are storing null-terminated strings that do not end with "\n".

A: you can also use 'endl' instead of '\n'
check this link: C++: "std::endl" vs "\n"


text:
Q: NSIS nsExec path issue perhaps First time with making an installation file. Using NSIS. Trying to run a nodeJS script command line after installation completes and poking about online suggestions all seem to be a variation of

Section "runNodeJavascript"
nsExec::Exec '"$SYSDIR\cmd.exe" /c
node "c:\Program Files (x86)\FolderOne\FolderTwo\JavascriptToRun.js"'
SectionEnd

But my experimentation so far is for naught, any insight? Everything else with NSIS online has been pretty helpful making a little installer but for some reason hitting a little barrier here...


text:
Q: Soldering iron for hakko t12 tips on 12v I considered getting those clone hakko t12 tip compatible soldering iron.
this is the tutorial I'm following:

https://www.instructables.com/id/DIY-Hakko-T12-Compatible-Soldering-Station/

so based from the title, I know you know what I am doing so i'll just get to the point already.
I'm building those soldering iron kit but I don't have the 24v power supply. I  have however a 12v power supply.
In theory, the soldering iron will still heat up but slower. I'm fine with slow so will it function or will the circuitry on the controller explode or something. Even if it is slow, As long as it is functioning, I'm fine with it.
This is what my soldering iron looks like:

https://www.ebay.com/itm/Digital-Soldering-Iron-Station-Temperature-Controller-Kits-For-HAKKO-T12-Handle/112555080925?hash=item1a34ce3cdd:m:mhF39lZBeOxALWWO8tNREIQ

A: Without following the links, your basic problem will be lack of power. The maximum power out of the iron is given by \$ P = \frac {V^2}{R} \$. If you halve the voltage you will only have a maximum of 1/4 of the iron's rated power.
The iron will heat up to the point that the rate of heat loss from the iron is equal to the power input. At 1/4 power I suspect that this may be below the melting point of your solder.

A: 75W @ 24V gets you up to 450'C
20W @ 12V might get you up to 150'C if you wait long enough and don't use it, at a rate of 60'C/W for thermal loss.
That won't melt solder very well, right?
What does Ohm's Law tell you when the resistance of the heater rises with filament temperature?


text:
Q: How can I tell whether Apache is using my .htaccess as intended? I want to prevent google from indexing pdf's on my website.
I have modified my .htaccess file to include the following lines, as suggested by google's webmaster tools:
<Files ~ "\.pdf$">
    Header set X-Robots-Tag "noindex, nofollow"
</Files>

I know that apache is running properly and reading my .htaccess file, because I can block access to the file entirely, but I cannot tell whether the above command is working.
The google webmaster tools claim that the crawlers can still see the pdfs, but they seem to be intended for only use with robots.txt. Is there a 3rd party tool (for linux) that I can use to check the meta tags with?

A: You could use wget on some of the PDFs and look at the headers:
wget -S http://host/something.pdf


text:
Q: Buildfire: Best way to allow user to upload photos Is there anything that is built into the Buildfire platform that would easily allow a user from the "Widget" to upload and post photos to the Buildfire server?

A: I think you are looking for this API.
https://github.com/BuildFire/sdk/wiki/File-System-Services
Then you want to pass your image to the get Server / CDN using
https://github.com/BuildFire/sdk/wiki/How-to-use-ImageLib#buildfireimagelibcropimageurl-options-cdn-mode
Keep in mind usage is limited to your app tier


text:
Q: Replace round brackets in MySQL I have a table with column productname.
Product name may contain round brackets.
My question is how I can replace round brackets while searching inside a query.
Let say product name is "kitkat(100gm)" and if the user searches for kitkat100, it should display "kitkat(100gm)"
My query is
Select * from products
where REPLACE(productname, '(', '') like REPLACE('%kitkat100%', '(', '')

Even if I use back-slash then too getting the same error.
Select * from products
    where REPLACE(productname, '\(', '') like REPLACE('%kitkat100%', '\(', '')

But this is giving me error
 #1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use near
 'LIMIT 0, 25' at line 1

How I can resolve this?

A: You're pretty close, but you don't have to include the replace in the 'LIKE' clause.  i.e.
SELECT *
FROM products
WHERE REPLACE(productname, '(', '') LIKE '%kitkat100%'


text:
Q: Geopandas Plot with label I have a geopandas file:
from shapely.geometry import Point, LineString
import geopandas

line1 = LineString([
    Point(0, 0),
    Point(0, 1),
    Point(1, 1),
    Point(1, 2),
    Point(3, 3),
    Point(5, 6),
])

line2 = LineString([
    Point(5, 3),
    Point(5, 5),
    Point(9, 5),
    Point(10, 7),
    Point(11, 8),
    Point(12, 12),
])

line3 = LineString([
    Point(9, 10),
    Point(10, 14),
    Point(11, 12),
    Point(12, 15),
])

gdf = geopandas.GeoDataFrame(
    data={'name': ['A', 'B', 'A']},
    geometry=[line1, line2, line3]
)

Now, I would like to plot it, but depending on the name "A", "B" ist should either be plotted in red or in black. My real dataset is much much larger. Therefore, a efficient solution would be highly appreciated. Thanks!

A: You could add a column with a numeric equivalent and define your own cmap. You can use 0 and 1 for A and B or 0, 0.5 and 1 for A, B and C and so on.
from shapely.geometry import Point, LineString
import geopandas
from matplotlib.colors import LinearSegmentedColormap
from matplotlib import pyplot as plt

line1 = LineString([
    Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 2),
    Point(3, 3), Point(5, 6),])

line2 = LineString([
    Point(5, 3), Point(5, 5), Point(9, 5), Point(10, 7),
    Point(11, 8), Point(12, 12),])

line3 = LineString([
    Point(9, 10), Point(10, 14), Point(11, 12), Point(12, 15),])

gdf = geopandas.GeoDataFrame(
    data={'name': ['A', 'B', 'A']},
    geometry=[line1, line2, line3]
)

my_cmap = LinearSegmentedColormap.from_list(
    'mycmap', [(0, 'red'), (1, '#000000')])

gdf['num'] = gdf['name'].replace({'A': 0, 'B': 1})

gdf.plot(cmap=my_cmap, column='num')
plt.show()


text:
Q: Line breaks from textarea and mysql dont appear in html How can I make text appear on diff lines in html?! They appear on diff lines in my text area when output from mysql, and also appear on diff lines inside mysql. But in the web page its all on one line. How can this be solved?

A: Use the PHP nl2br function:
$string = "hello \n world";
$string = nl2br($string);

It's quite self-explanitory: \n gets replaced with

A: Use:
string nl2br ( string $string [, bool $is_xhtml = true ] )

It can handle \n, \r, \r\n or \n\r linebreaks and replaces them with a

Example:
$yourText = "This is line one.\nThis is line two.";
$yourText = nl2br($yourText);
echo $yourText;

This will result in:
This is line one.
This is line two.

Link to the manual for more information.

A: Replace Linebreaks with

str_replace(.N, '
', [element]);

A: You can use
..Your text..
 tag for that.


text:
Q: Postgresql add item in array except if null I try to make a PostgreSQL array by using values from JSONB field.
When all data are in JSONB, result is fine. This query :
SELECT array [
    (SELECT ('{"tech_id": 4, "admin_id": 5}'::jsonb->>'admin_id')::int),
    (SELECT ('{"tech_id": 4, "admin_id": 5}'::jsonb->>'tech_id')::int)
];

returns me the right result because admin_id and tech_id are in JSONB field :
-[ RECORD 1 ]
array | {5,4}

But, if JSONB contains only one value, the array contains a NULL value.
This query :
SELECT array [
    (SELECT ('{"tech_id": 4}'::jsonb->>'admin_id')::int),
    (SELECT ('{"tech_id": 4}'::jsonb->>'tech_id')::int)
];

Gives me this result :
-[ RECORD 1 ]---
array | {NULL,4}

But I want an array like {4}, so without NULL value.
Do you know a way to avoid adding NULL value in this case ?

A: Finnaly, I found solution by wrapping the array to check if values are NULL.
I use the following code :
select array_agg(id) FROM unnest(array [
    (SELECT ('{"tech_id": 4}'::jsonb->>'admin_id')::int),
    (SELECT ('{"tech_id": 4}'::jsonb->>'tech_id')::int)
]) as id where id IS NOT NULL;

PostgreSQL returns the expected result :
-[ RECORD 1 ]--
array_agg | {4}


text:
Q: How do I install jdk on SUSE Linux with ansible? I need to install java on one of my VMs running SUSE Linux using ansible.
Below is the playbook code I am using:
- name: Download Java
  become_user: "{{user}}"
  command: "wget -q -O {{java_archive}} --no-check-certificate --no-cookies --header 'Cookie: oraclelicense=accept-securebackup-cookie' {{download_url}} creates={{java_archive}}"

- name: Fix ownership
  become_user: "{{user}}"
  file: state=directory path={{java_name}} owner={{user}} group={{user}} recurse=yes

- zypper: name={{download_folder}}/jdk-8u5-linux-x64.rpm become_user={{user}} state=present

- name: Clean up
  become_user: "{{user}}"
  file: state=absent path={{java_archive}}

The problem I'm facing is that the installer needs some interactions while installing. How do I automate that? Or there is some other way to achieve this?

As requested in comments, following message appears when I try to install without ansible.

A: From ansible-doc zypper:
- oldpackage
        Adds `--oldpackage' option to `zypper'. Allows to downgrade packages
        with less side-effects than force. This is implied as soon as a
        version is specified as part of the package name.
        (Choices: yes, no)[Default: no]

Try with oldpackage=yes and if it doesn't help you could use the more aggressive force=yes option.


text:
Q: Ionic Storage service with observables I'm using Ionic Storage in an Ionic 2 app and have been trying for the past few days to find the best way to implement a service that keeps the locally stored data in sync with the components.
I have no problem using Storage as-is (I can get set and get just fine), but making the service be able to sync data to the component, and then back to the service is the challenge.
I'm assuming the best way would be to utilize observables with rxjs, but I can't seem to find articles that aren't conflicting/inconsistent or not the use case I'm looking for. Most of them seem to have data only flowing 1 way. Reference 1 Reference 2
What would be the best way to keep a single Storage object (user, for example) in sync between the service and components while being able to modify it, such as using [(ngModel)] on a select element?

A: Maybe it is too late to anwser it. Ionic framework have changed a lot. And other useful framework have also come out. So I believe you already found your own anwser.
I think the best way is using singleton shared service or the like. The paradigm of flux, redux and ngrx/store is solution.
What you acheive is handling data in sync. But it is not possible (at least for now).
So possible way is that service
(or something) should modify data single-handed, while other components and services have to dispatch event to the service for modifying data. And then, they got identical modified data from the service. After all, sync holds.
For Ionic, I think singleton shared service and ngrx/store is available solution.


text:
Q: How to integrate web services with custom module in SugarCRM? I'm using SugarCRM to develop a software for customers management. I created a custom module from basic template with custom fields. Is it possible to get rid of SugarCRM db and perform CRUD operations through external web serivices? Actually I was able to show web services data in the datailview by setting the bean property of a custom controller.
class CustomerController extends SugarController{

public function action_detailview(){

        $customer = new Customer();
        $customer = getCustomerFromWebService();
        $this->bean = $customer;
        $this->view = "detail";

    }

}

I would like to do the same thing with listview, but I don't know how set the records of the list (if it exists) used by the default listview.

A: You can change list view by customizing view.list.php in custom/modules/modulename/views/view.list.php using following code:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

require_once('include/MVC/View/views/view.list.php');

// name of class match module
class modulenameViewList extends ViewList{

    // where clause that will be inserted in sql query
    var $where = 'like 'htc'';
    function modulenameViewList()
    {
        parent::ViewList();
    }

    /*
     * Override listViewProcess with addition to where clause to exclude project templates
     */
    function listViewProcess()
    {
            $this->lv->setup($this->seed, 'include/ListView/ListViewGeneric.tpl', $this->where, $this->params);
            echo $this->lv->display();
    }

}

?>


text:
Q: ¿Cómo indexar columnas tipo JSON en MySQL? Cuando creamos una tabla en MySQL, generalmente revisamos, que columnas son las indicadas para indexar y de este modo ayudar a realizar las búsquedas mas rápido
EJEMPLO
mysql> CREATE TABLE profile(
    -> id BIGINT PRIMARY KEY AUTO_INCREMENT,
    -> name VARCHAR(100) UNIQUE NOT NULL,
    -> INDEX(name),
    -> attributes JSON NOT NULL);
Query OK, 0 rows affected (1.34 sec)

Este es uno de los modos para indicar que la columna name se debe indexar, por que es una cadena de texto contenida
Sin embargo los datos de tipo JSON, siguen una estructura similar a la siguiente
'{"data": {"name": "alfredo", "age": 20, "email": "mail@mail.com"}}'

Llegados a este punto debemos respondernos lo siguiente

*

*Como se indexa una columna que guarda valores por clave/valor

*Como se indexa el valor de una columna en especifico

A: Siguiendo con el mismo ejemplo, tenemos la siguiente tabla
mysql> CREATE TABLE profile(
    -> id BIGINT PRIMARY KEY AUTO_INCREMENT,
    -> name VARCHAR(100) UNIQUE NOT NULL,
    -> attributes JSON NOT NULL);
Query OK, 0 rows affected (1.34 sec)

Sin embargo, al tener una columna JSON de este tipo
'{"name": "alfredo", "age": 20, "email": "mail@mail.com"}'

Debemos pensar primero en que tendremos que trabajar en columnas generadas, donde se almacene el valor de la clave/valor indexada
Primero creamos la nueva columna a la cual le indicamos el tipo, la longitud y con un alias la indicamos que clave del JSON va a contener
mysql> ALTER TABLE profile
    -> ADD attributes_data VARCHAR(150)
    -> AS (attributes->>"$.name");
Query OK, 0 rows affected (1.27 sec)
Records: 0  Duplicates: 0  Warnings: 0

Qué es ese operador ->>?

*

*Es el operador acortado de la función JSON_EXTRACT()
Bien ahora que ya tenemos la columna generada, debemos indicar que al tener ya solo un valor almacenado name este mismo será indexado
mysql> ALTER TABLE profile
    -> ADD INDEX(attributes_data);
Query OK, 0 rows affected (0.72 sec)
Records: 0  Duplicates: 0  Warnings: 0

EXPLICACIÓN

*

*Generamos una nueva columna(generated column) esta es la que guardara los datos de una sola clave de nuestro JSON es como una columna con datos filtrados

*usamos el operador ->> que es el acortado de JSON_EXTRACT() para indicar que clave del JSON debe extraer, además lleva doble signo de mayor que, para evitar que las cadenas de texto las regrese entre comilladaas

*Una vez que hemos creado la columna anterior, hacemos un ALTER indicando que esta columna será indexada

actualización
Si deseas usar la función JSON_EXTRACT() quedaría de este modo
mysql> ALTER TABLE profile
    -> ADD attributes_skills VARCHAR(150)
    -> AS (JSON_EXTRACT('attributes', '$.skills'));
Query OK, 0 rows affected (0.43 sec)
Records: 0  Duplicates: 0  Warnings: 0

finalmente hagamos un describe de la tabla recién creada para checar las características que posee
mysql> describe profile;
+-------------------+--------------+------+-----+---------+-------------------+
| Field             | Type         | Null | Key | Default | Extra             |
+-------------------+--------------+------+-----+---------+-------------------+
| id                | bigint(20)   | NO   | PRI | NULL    | auto_increment    |
| name              | varchar(100) | NO   | UNI | NULL    |                   |
| attributes        | json         | NO   |     | NULL    |                   |
| attributes_skills | varchar(150) | YES  |     | NULL    | VIRTUAL GENERATED |
+-------------------+--------------+------+-----+---------+-------------------+
4 rows in set (0.00 sec)


text:
Q: manipulation of subtraction I am trying to solve an induction problem and got stuck at this part.
$$ 1 - \frac{n+2}{(n+2)!} + \frac{n+1}{(n+2)!} = 1 - \frac{(n+2) - (n+1)}{(n+2)!} $$
Shouldn't it be
$$ 1 - \frac{n+2}{(n+2)!} + \frac{n+1}{(n+2)!} = 1 - \frac{(n+2) + (n+1)}{(n+2)!} $$
How do you get the left expression to the right expression?

A: Would you feel more comfortable with this?
$$1-\dfrac{n+2}{(n+2)!}+\dfrac{n+1}{(n+2)!}=1+\dfrac{(n+1)-(n+2)}{(n+2)!}$$
If you chose to, you could rewrite it from here to
$$1-[-\dfrac{(n+1)-(n+2)}{(n+2)!}]=1-\dfrac{(n+2)-(n+1)}{(n+2)!}$$

A: Note that
$$-\frac{A+B}{C}=(-1)\times \left(\frac{A+B}{C}\right)=(-1)\times\left(\frac{A}{C}+\frac{B}{C}\right)=-\frac{A}{C}-\frac{B}{C}=\frac{-A-B}{C}.$$
The minus sign in front of the first fraction does influence the plus sign in front of $B$ of the numerator of the first fraction.


text:
Q: How to specify what will be the export build js and css filenames in svelte I am using vite for svelte, I have attached vite.config.js below, I tried looking for references on the web but couldn't find any
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 4000
  },
  preview: {
    port: 4000
  },
  plugins: [
    svelte({
      compilerOptions: {
        customElement: true,
      }
    }),
  ]})

A: There are options for that under build > rollupOptions, e.g.
export default defineConfig({
    build: {
        rollupOptions: {
            output: {
                entryFileNames: '[name].js',
                assetFileNames: '[name].[ext]',
            },
        },
    },
    plugins: [
        svelte(),
    ],
});

Note that the generated hashes exist for caching purposes, if those are removed, you will have to take care of cache invalidation manually. For something like a component library that would not be an issue, of course.
There is an option build.manifest, that can be used to output mappings from original source to compiled output which could be used to determine the output name, rather than changing the above rollup options. E.g. if a server has to generate <script src="..."> tags, this can be used.


text:
Q: Как сделать переключение между окнами? Подскажите, пожалуйста, как можно сделать переключение/переходы между окнами? И еще один момент. Окна открываются со свойствами position:absolute;top и left - как это собственно и определено в стиле. А как сделать так, чтобы окна позиционировались под своими ссылками/идентификаторами, т.е. каждое окно выводилось чуть ниже своей ссылки? Благодарю за помощь!

$(document).ready(function() {
  var overlay = $('.overlay');
  var window = $('.window');
  var close = $('.close');
  $('.tab').bind('click', function() {
    $('.content').hide();
    $('#' + $(this).attr('id') + '-content').show();
    $('.tab').removeClass('tab-selected');
    $('[id=' + $(this).attr('id') + ']').addClass('tab-selected');
    overlay.show();
    window.show();
  });
  $('.close').on('click', function() {
    $('.content').hide();
    $('#' + $(this).attr('id') + '-content').hide();
    $('.tab').removeClass('tab-selected');
    overlay.hide();
    window.hide();
  });
});
.tab {
  cursor: pointer;
}

.tab-selected {
  background: green;
  color: #fff;
}

.window {
  display: none;
  z-index: 2;
  position: absolute;
  top: 20%;
  left: 20%;
  right: 0;
  bottom: 0;
  width: 200px;
  height: 100px;
  padding: 15px;
  background: gray;
}

.content {
  display: none;
  width: 100%;
  height: 100%;
  background: white;
}

.overlay {
  z-index: 1;
  position: fixed;
  background-color: #000;
  opacity: 0.7;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: none;
}

.close {
  display: block;
  position: absolute;
  top: 0;
  right: 0;
  cursor: pointer;
}

.prev,
.next {
  position: absolute;
  cursor: pointer;
  top: 50%;
}

.prev {
  left: 0;
}

.next {
  right: 0;
}

1

2

3

4

Текст 1

Текст 2

Текст 3

Текст 4

<

>

X

A:
Вопрос 1. Как можно сделать переключение/переходы между окнами?
  Вопрос 2. Как сделать так, чтобы окна позиционировались под своими ссылками/идентификаторами, т.е. каждое окно выводилось чуть ниже своей ссылки?

$('.next, .prev').on('click', function() {
    var obj = ($(this).hasClass("next")) ? $(this).closest(".window").find(".content:visible + .content") : $(this).closest(".window").find(".content:visible").prev(".content");
    var obj_id =  (obj.length > 0) ? obj.attr("id") : (($(this).hasClass("next")) ? '1-content': '4-content');
    var id = obj_id.split("-")[0];
    $(".content").hide();
    $("#" + obj_id).show();
    $(".tab").removeClass("tab-selected");
    $("#" + id).addClass("tab-selected");
    $(this).closest(".window").css("top", $("#" + id).offset().top + $("#" + id).height());
});

$(this).closest(".window") можно заменить на window, ввиду того, что window у Вас уже объявлено в начале кода.
Чтобы при открытии(при нажатии на блок .tab) окно отображалось под активным блоком tab, добавьте в конец обработчика $('.tab').bind('click', function() строку:
window.css("top", $(this).offset().top + $(this).height());

$(document).ready(function() {
  var overlay = $('.overlay');
  var window = $('.window');
  var close = $('.close');
  $('.tab').bind('click', function() {
    $('.content').hide();
    $('#' + $(this).attr('id') + '-content').show();
    $('.tab').removeClass('tab-selected');
    $('[id=' + $(this).attr('id') + ']').addClass('tab-selected');
    overlay.show();
    window.show();
    window.css("top", $(this).offset().top + $(this).height());
  });
  $('.close').on('click', function() {
    $('.content').hide();
    $('#' + $(this).attr('id') + '-content').hide();
    $('.tab').removeClass('tab-selected');
    overlay.hide();
    window.hide();
  });

  $('.next, .prev').on('click', function() {
    var obj = ($(this).hasClass("next")) ? window.find(".content:visible + .content") : window.find(".content:visible").prev(".content");
    var obj_id = (obj.length > 0) ? obj.attr("id") : (($(this).hasClass("next")) ? '1-content' : '4-content');
    var id = obj_id.split("-")[0];
    $(".content").hide();
    $("#" + obj_id).show();
    $(".tab").removeClass("tab-selected");
    $("#" + id).addClass("tab-selected");
    window.css("top", $("#" + id).offset().top + $("#" + id).height());
  });

});
.tab {
  cursor: pointer;
}

.tab-selected {
  background: green;
  color: #fff;
}

.window {
  display: none;
  z-index: 2;
  position: absolute;
  top: 20%;
  left: 20%;
  right: 0;
  bottom: 0;
  width: 200px;
  height: 100px;
  padding: 15px;
  background: gray;
}

.content {
  display: none;
  width: 100%;
  height: 100%;
  background: white;
}

.overlay {
  z-index: 1;
  position: fixed;
  background-color: #000;
  opacity: 0.7;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: none;
}

.close {
  display: block;
  position: absolute;
  top: 0;
  right: 0;
  cursor: pointer;
}

.prev,
.next {
  position: absolute;
  cursor: pointer;
  top: 50%;
}

.prev {
  left: 0;
}

.next {
  right: 0;
}

1

2

3

4

Текст 1

Текст 2

Текст 3

Текст 4

<

>

X

Дополнительно:

Начиная с jQuery 3.0, .bind () устарел. Он был заменен методом .on ()
для привязки обработчиков событий к документу с jQuery 1.7

UPD: если блоков больше 4, то ищем id последнего блока:
var obj_id = (obj.length > 0) ? obj.attr("id") : (($(this).hasClass("next")) ? '1-content' : window.find(".content").last().attr("id"));

$(document).ready(function() {
  var overlay = $('.overlay');
  var window = $('.window');
  var close = $('.close');
  $('.tab').bind('click', function() {
    $('.content').hide();
    $('#' + $(this).attr('id') + '-content').show();
    $('.tab').removeClass('tab-selected');
    $('[id=' + $(this).attr('id') + ']').addClass('tab-selected');
    overlay.show();
    window.show();
    window.css("top", $(this).offset().top + $(this).height());
  });
  $('.close').on('click', function() {
    $('.content').hide();
    $('#' + $(this).attr('id') + '-content').hide();
    $('.tab').removeClass('tab-selected');
    overlay.hide();
    window.hide();
  });

  $('.next, .prev').on('click', function() {
    var obj = ($(this).hasClass("next")) ? window.find(".content:visible + .content") : window.find(".content:visible").prev(".content");
    var obj_id = (obj.length > 0) ? obj.attr("id") : (($(this).hasClass("next")) ? '1-content' : window.find(".content").last().attr("id"));
    var id = obj_id.split("-")[0];
    $(".content").hide();
    $("#" + obj_id).show();
    $(".tab").removeClass("tab-selected");
    $("#" + id).addClass("tab-selected");
    window.css("top", $("#" + id).offset().top + $("#" + id).height());
  });

});
.tab {
  cursor: pointer;
}

.tab-selected {
  background: green;
  color: #fff;
}

.window {
  display: none;
  z-index: 2;
  position: absolute;
  top: 20%;
  left: 20%;
  right: 0;
  bottom: 0;
  width: 200px;
  height: 100px;
  padding: 15px;
  background: gray;
}

.content {
  display: none;
  width: 100%;
  height: 100%;
  background: white;
}

.overlay {
  z-index: 1;
  position: fixed;
  background-color: #000;
  opacity: 0.7;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: none;
}

.close {
  display: block;
  position: absolute;
  top: 0;
  right: 0;
  cursor: pointer;
}

.prev,
.next {
  position: absolute;
  cursor: pointer;
  top: 50%;
}

.prev {
  left: 0;
}

.next {
  right: 0;
}

1

2

3

4

5

6

7

Текст 1

Текст 2

Текст 3

Текст 4

Текст 5

Текст 6

Текст 7

<

>

X


text:
Q: Convert Git submodule to subtree How can I convert a git submodule (with a folder in the local file system as a remote) to a git subtree, preferably preserving the commit history of the submodule?

A: Alexander Mikhailian's script modified by @GaspardP did not work for me.
I modified it, and made an improvement. Now, the new subtrees will point to the same commit as the old submodules did. Previously, the script would simply download the latest commit from the target repositories, potentially causing compatibility issues.
https://gist.github.com/Nikita240/0c98cea8f53a15e69699cd8bc40657c4
#!/bin/bash -x
# This script will convert all your git submodules into git subtrees.
# This script ensures that your new subtrees point to the same commits as the
# old submodules did, unlike most other scripts that do this.
# THIS SCRIPT MUST BE PLACED OUTSIDE OF YOUR REPOSITORY!!!!!!!!!!
# Otherwise, the script will interfere with the git commits.
# Save the script in your home directory as `~/subtrees.sh`
# `cd` into your repository
# Run `~/subtrees.sh`
# Enjoy!

# extract the list of submodules from .gitmodule
cat .gitmodules |while read i
do
if [[ $i == \[submodule* ]]; then
    echo converting $i

    read i

    # extract the module's prefix
    mpath=$(echo $i | grep -E "(\S+)$" -o)

    echo path: $mpath

    read i

    # extract the url of the submodule
    murl=$(echo $i|cut -d\= -f2|xargs)

    echo url: $murl

    # extract the module name
    mname=$(basename $mpath)

    echo name: $mname

    # extract the referenced commit
    mcommit=$(git submodule status $mpath | grep -E "\S+" -o | head -1)

    echo commit: $mcommit

    # deinit the module
    git submodule deinit $mpath

    # remove the module from git
    git rm -r --cached $mpath

    # remove the module from the filesystem
    rm -rf $mpath

    # commit the change
    git commit -m "Removed $mpath submodule at commit $mcommit"

    # add the remote
    git remote add -f $mname $murl

    # add the subtree
    git subtree add --prefix $mpath $mcommit --squash

    # commit any left over uncommited changes
    git commit -a -m "$mname cleaned up"

    # fetch the files
    git fetch $murl master

    echo
fi
done
git rm .gitmodules
git commit -a -m "Removed .gitmodules"

A: The following bash script is based on Alexander Mikhailian's post (http://mikhailian.mova.org/node/233). I modified it slightly to call subtree add instead of read-tree. It will fetch the list of submodules from the .gitmodule and extract the module's prefix, name and url. It then removes each submodule and adds them back as a subtree at the same location.  It also adds the remote of each submodule as a remote so you can update the subtree by providing its name instead of its url later on (i.e. git subtree pull -P Foo Foo master --squash instead of git subtree pull -P Foo https://example.com/foo.git master --squash)
You may remove the --squash argument if you want to import the full history of the subtree to your repository. With --squash, will only import the head of the subtree into your repository. This should probably be what most people want.
For more information, you may want to read this post by atlassian: http://blogs.atlassian.com/2013/05/alternatives-to-git-submodule-git-subtree/
#!/bin/bash -x
# extract the list of submodules from .gitmodule
cat .gitmodules |while read i
do
if [[ $i == \[submodule* ]]; then
    echo converting $i

    # extract the module's prefix
    mpath=$(echo $i | cut -d\" -f2)

    # skip two lines
    read i; read i;

    # extract the url of the submodule
    murl=$(echo $i|cut -d\= -f2|xargs)

    # extract the module name
    mname=$(basename $mpath)

    # deinit the module
    git submodule deinit $mpath

    # remove the module from git
    git rm -r --cached $mpath

    # remove the module from the filesystem
    rm -rf $mpath

    # commit the change
    git commit -m "Removed $mpath submodule"

    # add the remote
    git remote add -f $mname $murl

    # add the subtree
    git subtree add --prefix $mpath $mname master --squash

    # fetch the files
    git fetch $murl master
fi
done
git rm .gitmodules


text:
Q: Using "Open with" on windows applications Let's say I'm making my own programming language, and it has its own scripting file extension.
Then the user, let's say, drags their script file of whatever program they made onto the .exe of the programming language
How, programmatically, could the programming language figure out how to use the fact that they "opened the script" by dragging it on the .exe, as a means to run the script?


text:
Q: QML ListView: How to disable autoscrolling when new elements inserted? Does anybody knows, how to prevent scrolling down QML ListView when I prepend some elements to its head? I want to update ListView in a Twitter-like manner, when it always keeps its position and only explicit flick is possible.

A: Actually the insert function did the job.  You can insert it at the top or any desired position like this modelName.insert(0,{object});. A working example is here.
import QtQuick 1.0

Rectangle {
    id: rectangle1
    width: 320
    height: 480

    ListModel {
        id: cModel
        ListElement {
            name: "Bill Smith"
            number: "555 3264"
        }
        ListElement {
            name: "John Brown"
            number: "555 8426"
        }
        ListElement {
            name: "Sam Wise"
            number: "555 0473"
        }
    }
    ListView {
        id: list_view1
        width: rectangle1.width
        height: rectangle1.height - 40
        anchors.horizontalCenter: parent.horizontalCenter
        delegate: Text {
            text: name + ": " + number
        }
        model: cModel
    }

    Rectangle {
            id: rectangle2
            width: 320
            height: 40
            color: "#ffffff"
            anchors.top: list_view1.bottom

            Text {
                id: text1
                text: qsTr("Click to add!")
                anchors.horizontalCenter: parent.horizontalCenter
                anchors.verticalCenter: parent.verticalCenter
                font.pixelSize: 16
                MouseArea {
                    id: mouse_area1
                    anchors.fill: parent
                    onClicked: addNewItemTop();
                }
            }
        }

    function addNewItemTop()
    {   var i = Math.random();
        cModel.insert(0,{"name" : "New Number", "number":i.toString()});
    }
    }


text:
Q: Issue Connecting tableView to Data Source in .XIB So I'm trying to connect a tableView component to a UIViewController created through the .xib user interface.  I am getting the classic -[UIView tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x1f544cb0 and am guessing that I have connected something incorrectly or am doing something that I shouldn't be doing with the interface builder.  I have searched google and stack overflow and have found similar questions but non with answers that have helped my situation.  I have been hitting my head trying to figure this out and hope someone here can help.  I have only ever done this through storyboard or with .xib when the controller was a UITableViewController.  Usually I would just use a UITableViewController but I may need to add a toolbar on the bottom of the view so that option is not viable. Here are the steps I took to create the class please let me know if I am doing something wrong
I first create the file with an XIB for user interface:

I then add the table view component to the XIB:

In the LeftMenuViewController.h I add the following line of code to tell the allow for the class to be used as a UITableViewDelegate and UITableViewDataSource:
@interface LeftMenuViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
I then connect the table view component up to the delegate and data source by control dragging from the component to the File's Owner heading and selecting the delegate and data source as can be seen:

I then add the following lines of code to LeftMenuViewController.m to provide definitions for the required TableView delegate methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 48;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    return cell;
}

This process causes the app to throw a NSInvalidArgumentException which produces the [UIViewController tableView:numberOfRowsInSection:]: unrecognized selector error.  What am I doing wrong?  Everything I have tried or have been recommended hasn't worked.

A: The fact that the error is referencing UIViewController in your error message, [UIViewController tableView:numberOfRowsInSection:]: unrecognized selector, that means that the file owner has not been set (it should be referencing your view controller subclass, not UIViewController, itself). You've correctly specified the delegate and data source in your NIB, so I wonder how you instantiated your view controller.
You should have instantiated it with something like:
SecondViewController *controller = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
[self presentViewController:controller animated:YES completion:nil];

Or, if the NIB name doesn't match the name of the controller:
SecondViewController *controller = [[SecondViewController alloc] initWithNibName:@"MyNibName" bundle:nil];
[self presentViewController:controller animated:YES completion:nil];

A: Click on File's Owner in your NIB file in the Placeholders section and make sure the custom class is set to LeftMenuViewController or whatever you named it.

A: In viewDidLoad:
self.tableView.delegate = self;


text:
Q: pasar URL metodo encriptado sin que se corte PHP El problema que tengo es el siguiente:
Estoy realizando un proyecto, el cual me trae por URL GET una palabra encriptada que contiene el símbolo / y el navegador lo corta ya que este entiende que debe cortar en esa linea
Ejemplo:
1atCXYEBTttPaGtVGcFtzKwnLyylko1gpmSm1/SM=

Al pasar esta encriptacion por URL al llegar a la barra divisoria (  /  ) el navegador no agrega los caracteres faltantes que son SM= y el proyecto me comienza a mostrar FATAL ERROR.
Como podría solucionar este tema, ya que si o si debo pasar por GET
Gracias.

A: Podrías usar la siguiente función para codificar la url:
urlencode("1atCXYEBTttPaGtVGcFtzKwnLyylko1gpmSm1/SM=");


text:
Q: How to fix cURL SSL connection timeout that only happens the first time the script is called I'm facing a strange problem using cURL with PHP on a Windows server. I have a very basic code that I'm using to test this issue (pretty much straight from the php cURL manual page):
<?php
// In this example we are referring to a page that handles html
$headers = array( "Content-Type: text/html");

// Initialise Curl
$curl = curl_init();

if ($curl === false)
    throw new Exception(' cURL init failed');

// Configure curl for website
curl_setopt($curl, CURLOPT_URL, "https://google.com");

// Set up to view correct page type
curl_setopt($curl, CURLOPT_HTTPHEADER, &$headers);

// Turn on SSL certificate verfication
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);

// Tell the curl instance to talk to the server using HTTP GET
curl_setopt($curl, CURLOPT_HTTPGET, 1);

// 1 second for a connection timeout with curl
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);

// Try using this instead of the php set_time_limit function call
curl_setopt($curl, CURLOPT_TIMEOUT, 60);

// Causes curl to return the result on success which should help us avoid using the writeback option
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

if( ! $result = curl_exec($curl))
    $result = curl_error($curl);

curl_close($curl);

echo var_dump($result);
?>

Sorry for the code dump, but it's pretty basic code and all it does is try to GET the google.com site using HTTPS (SSL).
The problem is that the first time this script is called, the response is always this: string(22) "SSL connection timeout".
Subsequent calls to the script output the desired result, but, if I wait a couple of minutes before calling the script again, the timeout issue happens again.
So, steps to reproduce the "error":

*

*Call the script -> timeouts

*Call the script again -> works fine

*Call the script one more time -> works fine

*Call the script n more times -> works fine

*Wait 10 minutes

*Call the script -> timeouts

*Call the script n more times again -> works fine

If I call any other script the response is immediate, even after a period of inactivity, so this behaviour only happen when cURL is involved.
All components are running the latest stable version, including PHP, cURL, OpenSSL, etc. The server is running Windows 2012 with IIS 8, latest upgrades, running PHP on FastCGI.
Does anyone have any idea on how I can solve this? Currently I have a cron job running every 5 minutes and calling the script above to refresh cURL, but that feels like a hack :(
Thanks.


text:
Q: Google search is not working in Ubuntu 18.04 I have a very peculiar problem. Sometimes Google search is not working. But if you type the website directly it works. Now to check whether it is a problem with my network, I connected the LAN to my laptop working on windows 10 and its working fine.

A: You probably solved it, but I will write it anyway:
Go to the IP network settings and check what is there in DNS settings.
Add to them the google DNS (8.8.4.4).
I had similar issues when I was only using 1.1.1.1 and 9.9.9.9
It seems that google doesn't want to leave you unattended...


text:
Q: Usage of raw SQL in EF Core 6 I am currently trying to find different areas where Linq is not sufficient and FromSqlRaw or ExecuteSqlRaw have to be used.
Some examples I have found are

*

*Bulk updates https://learn.microsoft.com/en-us/ef/core/performance/efficient-updating

*Executing stored procedures https://learn.microsoft.com/en-us/ef/core/querying/raw-sql
However I am looking for more areas where Linq does not perform good enough and even queries that cannot be generated from Linq in EF Core when it comes to database access.
My goal is to find poor performing Linq translations and examine the cause.

A: This is a bit of a solution looking for a problem. Given an application and looking for inefficiencies that might benefit from a different approach is something I would start off using a profiler and observing the database access in as close to a production capacity as I am allowed to get.
EF is like any tool, it can be leveraged to create works of art, and it can be abused and misused to create shanties. Even when done correctly, optimizations like indexes are something that are tuned based on looking at real-world options. There are many options that I would look at to address performance issues before considering direct to SQL. Typical culprits that can be easily identified via profiling:

*

*Lazy loading. (Dozens to hundreds of queries following up a "main" query.)

*Over-use of eager loading. (Queries involving a heck of a lot of joins)

*Sloppy use of client-side evaluation. (Either enabling that feature in EF Core, or slapping a ToList somewhere when a query complains to "fix" it, AsSplitQuery can help here, Projection is a better solution in most cases)

*Lack of pagination where more data is returned than necessary. (Similar to #3, having methods like "GetAll" and then applying filtering, pagination, etc.)

*Giving users too much flexibility in querying that they don't need 99% of the time, but in that 1% someone does try it, grinds the system to a halt. (Giving users filters/sorts on ALL columns and performing things like string.Contains by default for text searches)

*Giving users access to expensive, but necessary queries in real-time. (Big, justified queries, but being run against the production dataset and not "throttled" by something like a Queue to ensure too many of these monsters don't get run at once.)

Those are some of the top culprits that come to mind around performance, and none of them resort to going to SQL. Batch processing in your list is certainly one case that I believe does deserve looking outside of Linq, and potentially outside of EF all-together.  Stored Procs I am mixed on. If there is business logic that is shared between an EF-supported application and another existing system and I want to share that business logic as-is. The trouble is that if I'm relying on the Sproc for business rules then there's little point to EF, and if I'm splitting business rules between C#/EF and Sprocs, then that's having to manage logic in two locations.


text:
Q: define visibility in system verilog Are defines declared in a sv file visible in the next file if -mfcu option is not given?
With -mfcu option [and in verilog too], defines declared in one file are definitely visible to the next file.

A: No. The default in ModelSim/Questa is Single File Compilation Unit. The means that each file on the command line is a considered a separate compilation unit ( `include files are always part of the same compilation unit of the file that included them regardless). defines, types, functions, tasks, etc. defined in one compilation unit are not visible to another compilation unit. This is the same as C/C++ compilation and is our preferred setting.
For backward compatibility with Verilog, all Verilog files are compiled in a single compilation unit. The switch -mfcu puts both Verilog and SystemVerilog files (Multiple File Compilation Unit) in a single compilation unit.
Note that when you compile your code in separate compilation steps, each step creates a separate compilation unit. This example script creates 4 compilation units.
vlog -mfcu file1.sv file2.sv #compilation unit 1
vlog -mfcu file3.sv file4.sv #compilation unit 2
vlog file5.sv file6.sv       #compilation units 3 and 4