Q: Input validation : Remove value on backspace I am running into a query; I have multiple html input box on my webpage, even inside multiple table column where user can edit for business calculations.

*

*Text box support positive as well as negative value

*maxlength etc etc....

Problem is when user enter value in any text box; there are four ways he can clear the value if he intend to type another.

*

*backspace or delete  - working fine

*ctrl A + delete - working fine

*ctrl A + backspace - working fine

*select all text using mouse left click and dragging it to select
text + backspace/delete

Fourth case is failing. Kindly help in 4th scenario.
Code:
<input type="text" id="tust"/>

$(document).ready(function(){
document.getElementById('tust').onblur = issueDes;

$("input").on("keyup keydown",function (e) {
                if(this.value!='-')
                    while(isNaN(this.value))
                     this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'').split('').reverse().join('');

               });
});
function issueDes() {
    $("#tust").val(this.value+"%");
}

Fiddle:
DEMO - MOST CLOSE I CAN RE-CREATE THIS SCENARIO

A: Detect selction and keyCode. Hope this will work for you. Only selected value will remove.
arr = [08,127,46];
$(document).ready(function(){

document.getElementById('tust').onblur = issueDes;

$("input").on("keyup keydown",function (e) {
     var checkCode = $.inArray( e.keyCode, arr );
    if (window.getSelection) {
        var selectionRange = window.getSelection ().toString ();
        if((selectionRange.length > 0) && (checkCode != -1)){
        var value = $("#tust").val();
            $("#tust").val(value.replace(selectionRange,""))
        }
    }

                if(this.value!='-')
                    while(isNaN(this.value))
                     this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'').split('').reverse().join('');

               });
});
function issueDes() {
    var currVal = this.value;
    if(currVal != "" && currVal.indexOf("%") == -1){
    $("#tust").val(this.value+"%");
    }
}

demo http://jsfiddle.net/farhanbaloch/awug6h9a/6/


Q: Field set toggle on page load I have a similar code to this. but I'd like to have the fieldset toggled when the page load. Also, show and hide when someone click on legend
<fieldset>
  <legend class="hide">Tags</legend>
  <div>
    <label>
     <input type="checkbox" name="col" value="summary"
       checked="checked" />
       Name
    </label>
   <label>
      <input type="checkbox" name="col" value="lastname" />
     LastName
   </label>
  </div>
</fieldset>

JQuery
$(function(){
$('legend').click(function(){
    $(this).nextAll('div').toggle();
    $(this).hasClass('hide')?($(this).attr("class", "show")):
 ($(this).attr("class", "hide"));
  });
})


Q: Eclipse "go to definition" problem I'm using PyDev for eclipse and am experiencing some issues with "go to definition". It works for most modules, but for some site packages it does not. It does the "bump" sound and then nothing happens. One of the packages that doesn't work is Twisted, which is weird since the source is included and right there. Any idea how to fix this?

A: The go to definition works just fine. The problem was that eclipse didn't know where to find the source. You can go to window > preferences > pydev > interpreter > New folder, and add the folders missing. Even though you've added site-packages to the configuration, you still have to add subfolders separately to get code assist and to be able to go to the definition.

A: Pydev (also bundle with the Aptana distro) does not seem to have any bug exactly similar to the one you are describing.
Here is the list of bugs including the word "definition" for PyDev: bugs
You could open a bug report there with the exact version of eclipse, pydev, java used
But first:
What version of Pydev are you using? The open-source one or the commercial one (i.e. open-source + Pydev extensions)?
Because the matrix feature is quite clear:
Feature List        Pydev "Open Source"     Pydev Extensions
---------------------------------------------------------------
Go to definition    BRM*                    Pydev Extensions(2)

BRM*: Bicycle Repair Man is an open-source program that provides 'go-to-definition' and refactoring. Its 'go-to-definition' only works for Python, and only works 'well' for global or local tokens (does not work very well on methods from parameters or on 'self'). It is currently 'unsupported'.
Pydev Extensions (2): Pydev extensions provides a 'go-to-definition' that works for python and jython, and should work even on methods from parameters and 'self'.


Q: SQLite3 with PHP How to do Cross Referencing of Columns with data found in other Columns Here is how my Sample data looks like
hwid: 1502e3c3-b49c-4907-92fd-2ffac2d50ace
ip: 68.197.140.109
character name: none

hwid: 1502e3c3-b49c-4907-92fd-2ffac2d50ace
ip: 219.100.37.236
character name: none

hwid: 1502e3c3-b49c-4907-92fd-2ffac2d50acd
ip: 68.197.140.109
character name: kalgame

Now say I'm logging in with
this hwid
1502e3c3-b49c-4907-92fd-2ffac2d50ace
and this ip address
219.100.37.236
which has a link to using a previous IP address of 68.197.140.109
and that IP address has a link to a 3rd hwid that has a character name : kalgame.
Thats what I need to do cross referencing with all IP's linked to all hwid's and then check if any of those hwid's have a character_name.
If they have a character_name associated to them return them in a SELECT DISTINCT COUNT(totalMatchesOfUniqueCharacterNames)
I also need to check if the current HWID or current IP you are using has 3 days trial period, if it does then also add it to the SELECT DISTINCT COUNT.. then I could easily check in PHP if SELECT DISTINCT COUNT is greater then 1, then abort giving out any more free trials to the specific user as he already logged in before with a character_name, and also maybe had a 3 day trial period before hand on either his PC hwid or his IP address, note I would also like to exclude blank character_name's as those players didn't login with a character yet.. so they don't count. I also have to match the locale which is which game are they playing if they are playing a different game then they also don't count.
Here is my attempt at cross referencing I been working at this for 6 hours and today is my first day using SQLite or any SQL in general so I have no clue what i'm doing
Here is my table schema DDL for both tables.. they are also both in the same database file.
CREATE TABLE ips (
    hwid           VARCHAR,
    ip             VARCHAR,
    character_name VARCHAR,
    locale         VARCHAR,
    botver         VARCHAR,
    reg_time       DATETIME,
    last_time      DATETIME,
    ping_count     INTEGER  DEFAULT 0
);

CREATE TABLE users (
    hwid      VARCHAR UNIQUE,
    timestamp INTEGER,
    daysToUse INTEGER,
    pcLimit   INTEGER,
    comment   VARCHAR
);

Here is my attempt at putting it all together
SELECT users2.hwid,
       ips2.character_name,
       ips2.ip
  FROM users AS users2
       INNER JOIN
       ips AS ips2 ON ips2.hwid = users2.hwid
 WHERE EXISTS (
           SELECT 1
             FROM users
                  INNER JOIN
                  ips ON ips.hwid = users.hwid
            WHERE ips.character_name != '' AND
                  ips.locale = ips2.locale AND
                  (ips.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' OR
                   ips.ip = '219.100.37.236') AND
                  EXISTS (
                          SELECT 1
                            FROM users
                                 INNER JOIN
                                 ips ON ips.hwid = users.hwid
                           WHERE ips.character_name != '' AND
                                 ips2.ip = ips.ip AND
                                 ips2.locale = ips.locale
                      )
       )
OR
       (ips2.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' AND
        users2.daysToUse = 3) OR
       (ips2.ip = '219.100.37.236' AND
        users2.daysToUse = 3);

Here is what I left in the production website.. which isn't that good.. doesn't do cross referencing that well skips certain columns but atleast it kinda works unlike the top code above which just sounds like it should work but doesn't work at all.
SELECT COUNT(DISTINCT users2.hwid)
  FROM users AS users2
       INNER JOIN
       ips AS ips3 ON ips3.hwid = users2.hwid
 WHERE ips3.character_name = (
                                 SELECT ips.character_name
                                   FROM users,
                                        ips AS ips2
                                        INNER JOIN
                                        ips ON ips.hwid = users.hwid
                                  WHERE ips.character_name != '' AND
                                        ips.locale = ips2.locale AND
                                        (ips.hwid = '$HWID' OR
                                         ips.ip = '$IP')
                             )
OR
       (ips3.hwid = '$HWID' AND
        users2.daysToUse = 3) OR
       (ips3.ip = '$IP' AND
        users2.daysToUse = 3);

If anyone can help me out i will be forever grateful :D

A: Since your subqueries share same FROM and JOIN clauses, simplify to a compact WHERE clause:
SELECT i.ip, i.character_name, u.hwid, u.daysToUse, i.locale
FROM users u
INNER JOIN ips i
   ON i.hwid = u.hwid
WHERE (i.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace'
        AND u.daysToUse = 3)
   OR (i.ip = '219.100.37.236' AND u.daysToUse = 3)
ORDER BY i.last_time

A: Solved it myself.. turns out it is very simple to do this, I just had the query done in backwards order I flipped the order and bam it works as expected.
The locale problem was hard.. I couldn't detect which locale is currently used, so I relayed on using ips.lasttime which shows which IP or HWID was used last, and being used last its obviously the locale I want to check
Final result
SELECT ips.ip,
       ips.character_name,
       users.hwid,
       users.daysToUse,
       ips.locale
  FROM users
       INNER JOIN
       ips ON ips.hwid = users.hwid
 WHERE ips.ip IN (
           SELECT ips.ip
             FROM users
                  INNER JOIN
                  ips ON ips.hwid = users.hwid
            WHERE (ips.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' AND
                   users.daysToUse = 3) OR
                  (ips.ip = '219.100.37.236' AND
                   users.daysToUse = 3)
       )
AND
       ips.locale = (
           SELECT ips.locale
             FROM users
                  INNER JOIN
                  ips ON ips.hwid = users.hwid
            WHERE (ips.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' AND
                   users.daysToUse = 3) OR
                  (ips.ip = '219.100.37.236' AND
                   users.daysToUse = 3) ORDER BY ips.last_time ASC
       );


Q: Polynomial Expansion from scratch with numpy/python I am building a polynomial regression without using Sklearn.
I'm having trouble with Polynomial Expansion of features right now.
I have a dataframe with columns A and B.
When I imported and ran PolynomialFeatures(degree of 2) from Sklearn, I found that it returns 6 different features.
I understand that 2 features became 6 features because it is (A + B + Constant)*(A + B + Constant)
which becomes A2 + 2AB + 2AC + 2BC + B2 + C2, 6 different features. I am trying to recapitulate this with Python and Numpy.
As there is constant c, I created a new column C to my dataframe. However, I am very stuck on how to proceed after this. I tried for loop for (number of features * degree #) times but got confused for the combination of features.
'''
    def polynomial_expansion(features_df, order):

        return expanded_df

'''
Can someone help me out? What would be Python/Numpy/Pandas method I can use for this situation?
Thank you.

A: I created a simple example of what you need to do in order to create your polynomial features from scratch. The first part of the code creates the result from Scikit Learn:
from sklearn.preprocessing import PolynomialFeatures
import pandas as pd
import numpy as np

df = pd.DataFrame.from_dict({
    'x': [2],
    'y': [5],
    'z': [6]})

p = PolynomialFeatures(degree=2).fit(df)
f = pd.DataFrame(p.transform(df), columns=p.get_feature_names(df.columns))
print('deg 2\n', f)
p = PolynomialFeatures(degree=3).fit(df)
f = pd.DataFrame(p.transform(df), columns=p.get_feature_names(df.columns))
print('deg 3\n', f)

The result looks like:
deg 2
      1    x    y    z  x^2   x y   x z   y^2   y z   z^2
0  1.0  2.0  5.0  6.0  4.0  10.0  12.0  25.0  30.0  36.0
deg 3
      1    x    y    z  x^2   x y   x z   y^2   y z   z^2  x^3  x^2 y  x^2 z  x y^2  x y z  x z^2    y^3  y^2 z  y z^2    z^3
0  1.0  2.0  5.0  6.0  4.0  10.0  12.0  25.0  30.0  36.0  8.0   20.0   24.0   50.0   60.0   72.0  125.0  150.0  180.0  216.0

Now to create a similar feature without Scikit Learn, we can write our code like this:

row = [2, 5, 6]

#deg = 1
result = [1]
result.extend(row)

#deg = 2
for i in range(len(row)):
    for j in range(len(row)):
        res=row[i]*row[j]
        if res not in result:
            result.append(res)
print("deg 2", result)

#deg = 3
for i in range(len(row)):
    for j in range(len(row)):
            for z in range(len(row)):
                res=row[i]*row[j]*row[z]
                if res not in result:
                    result.append(res)
print("deg 3", result)

The result looks like:
deg 2 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36]
deg 3 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36, 8, 20, 24, 50, 60, 72, 125, 150, 180, 216]

To get the same results recursively, you can use the following code:
row = [2, 5, 6]
def poly_feats(input_values, degree):
    if degree==1:
        if 1 not in input_values:
            result = input_values.insert(0,1)
        result=input_values
        return result
    elif degree > 1:
        new_result=[]
        result = poly_feats(input_values, degree-1)
        new_result.extend(result)
        for item in input_values:
            for p_item in result:
                res=item*p_item
                if (res not in result) and (res not in new_result):
                    new_result.append(res)
        return new_result

print('deg 2', poly_feats(row, 2))
print('deg 3', poly_feats(row, 3))

And the results will be:
deg 2 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36]
deg 3 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36, 8, 20, 24, 50, 60, 72, 125, 150, 180, 216]

Also, if you need to use Pandas data frame as an input to the function, you can use the following:
def get_poly_feats(df, degree):
    result = {}
    for index, row in df.iterrows():
        result[index] = poly_feats(row.tolist(), degree)
    return result


Q: Git commit is incredibly slow Lately when I use git commit after changing a few lines of code, it may take a few minutes to finish. I'm unsure what has changed.
When I run it with diagnostics:
 GIT_TRACE2_PERF=1 git commit -m "message"

I get a verbose output, which hangs for at least a minute on this line. After a long time it moves on to print other lines.
... Some more lines ...
14:17:21.697862 trace2/tr2_tgt_perf.c:213    | d1 | main                     | atexit       |     |  0.024188 |           |              | code:0

Any ideas what may be causing this?


Q: FormatException of DateTime.Parse. Check which part is wrong in my date string I'd like to validate a date string in my TextBox.
If I have 2018-06-07 string in my TextBox, I can parse it with success with DateTime.TryParse or DateTime.Parse.
But if I have 2018-12-35 in my TextBox, the DateTime.Prase throws FormatException that is absolutely right.
How can I determine which part of DateTime is wrong. For Example how to determine if Day or Month is wrong.

A: DateTime.Parse tries a number of formats - some to do with the current culture, and some more invariant ones. It looks like it's including an attempt to parse with the ISO-8601 format of "yyyy-MM-dd" - which is valid for your first example, but not for your second. (There aren't 35 days in December.)
As it's trying to parse multiple formats, it doesn't necessarily make sense to isolate which part is "wrong" - different parts could be invalid for different formats.
How you should tackle this depends on where your data comes from. If it's meant to be machine-readable data, it's best to enforce a culture-invariant format (ideally ISO-8601) rather than using DateTime.Parse: specify the format you expect using DateTime.ParseExact or DateTime.TryParseExact. You still won't get information about which part is wrong, but it's at least easier to reason about. (That will also make it easier to know which calendar system is being used.)
If the data is from a user, ideally you'd present them with some form of calendar UI so they don't have to enter the text at all. At that point, only users who are entering the text directly would produce invalid input, and you may well view it as "okay" for them to get a blanket error message of "this value is invalid".
I don't believe .NET provides any indication of where the value was first seen to be invalid, even for a single value. Noda Time provides more information when parsing via the exception, but not in a machine-readable way. (The exception message provides diagnostic information, but that's probably not something to show the user.)
In short: you probably can't do exactly what you want to do here (without writing your own parser or validator) so it's best to try to work out alternative approaches. Writing a general purpose validator for this would be really hard.
If you only need to handle ISO-8601 dates, it's relatively straightforward:

*

*Split the input by dashes. If there aren't three dashes, it's invalid

*Parse each piece of the input as an integer. That can fail (on each piece separately)

*Validate that the year is one you're happy to handle

*Validate that the month is in the range 1-12

*Validate that the day is valid for the month (use DateTime.DaysInMonth to help with that)

Each part of that is reasonably straightforward, but what you do with that information will be specific to your application. We don't really have enough context to help write the code without making significant assumptions.


Q: SQL - reset cumulative value while keeping historical data I've been encharged, during my university internship, to create a web application to manage maintenace operations in the factory I work in. I'm an industrial engineer with just a little knowledge about database programming, so maybe this question will sound easy to you, I apologize.
That's the situation: the item is a mold, which needs ordinary maintenance after a number of operations (huge number, I'm talking about tiles manufacturing, and the maintenance frequency can be assumed as a mean value of once per year). I set up a database and the web application connected to it, and I created a view with the molds' list and the relative cumulative work, so that the department's responsible can have a fast perspective of the situation and see which molds need maintenance, and that works fine.
The problem is they "labeled" the molds, and I used that number as the row ID in the database. When the maintenance is performed the cumulative work needs to be resetted, but he wants to keep historical data about working operations.
Thus, what I need to do now, is "tell the system" when an item is manteined, then it has to reset the cumulative value while keeping historical data.
Values for the view I created are taken from 2 different tables: Molds and UnmountingOperations. In the latter there are information about which press the mold has been mounted on and the total work done during that operation. I thougt the solution is in the use of triggers, but I'd would like to ask:
What's the best practice to do so?
here you are the scripts created by SqlServer management studio.Sorry but record names are in Italian.
mold table:
CREATE TABLE [dbo].[Stampo](
[ID] [int] NOT NULL,
[Formato] [nchar](10) NOT NULL,
[n∞ uscite] [int] NULL,
[Spessore] [nchar](10) NULL,
[Descrizione] [nvarchar](max) NULL,
[Fornitore] [nvarchar](50) NULL,
CONSTRAINT [PK_Stampo] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,       ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

press table:
CREATE TABLE [dbo].[Pressa](
[Numero] [int] NOT NULL,
[Modello] [nchar](10) NULL,
CONSTRAINT [PK_Pressa] PRIMARY KEY CLUSTERED
(
[Numero] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

association mold-press for unmounting operations(mq_pressati) is the work amount driver,stands for square meters pressed:
CREATE TABLE [dbo].[SmontaggioStampi](
[NumeroPressa] [int] NOT NULL,
[IDStampo] [int] NOT NULL,
[DataSmontaggio] [datetime] NOT NULL,
[mq_pressati] [int] NOT NULL,
[Descrizione] [nvarchar](max) NULL,
CONSTRAINT [PK_Produzione presse] PRIMARY KEY CLUSTERED
(
[NumeroPressa] ASC,
[IDStampo] ASC,
[DataSmontaggio] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[SmontaggioStampi]  WITH CHECK ADD  CONSTRAINT  [FK_SmontaggioStampi_Pressa] FOREIGN KEY([NumeroPressa])
REFERENCES [dbo].[Pressa] ([Numero])
GO

ALTER TABLE [dbo].[SmontaggioStampi] CHECK CONSTRAINT [FK_SmontaggioStampi_Pressa]
GO

ALTER TABLE [dbo].[SmontaggioStampi]  WITH CHECK ADD  CONSTRAINT [FK_SmontaggioStampi_Stampo] FOREIGN KEY([IDStampo])
REFERENCES [dbo].[Stampo] ([ID])
GO

ALTER TABLE [dbo].[SmontaggioStampi] CHECK CONSTRAINT [FK_SmontaggioStampi_Stampo]
GO

A: As for best practices, "avoid triggers like the plague" is the best advice I could give you.
What I've done in a similar situation is to add a column that indicates that a row is now archived.  I used a datetime column called ArchivedDt.  Normal queries exclude this column like:
where  ArchivedDt is null

You can even do this in a view.  The hierarchical data is still there, and a specific archive run can be easily undone.


Q: How to to duplicate a 4 partitions image on an eMMC from U-Boot? I have an image (more specifically a wic image for those who are familiar with Yocto framework) that contains a partition table along with its 4 partitions. It's size is bit less than 1GB.
In order to write this image to the eMMC:

*

*I first load it to RAM through TFTP

=> tftp 0x600000000 <image>.wic

*

*Then I write the image from RAM to the eMMC

=> mmc write 0x600000000 0x0 0x1FFFFF

*

*The image gets written correctly and I can list the 4 partitions. So far, so good.

=> mmc part

Partition Map for MMC device 1  --   Partition Type: EFI

Part    Start LBA       End LBA         Name
        Attributes
        Type GUID
        Partition GUID
  1     0x00000800      0x0000681f      "boot"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   cd5df8ce-ded3-4cf4-b364-33d7a4b24953
  2     0x00006820      0x000139e7      "first"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   3acc4557-2273-462a-a2bd-d130b3a5745d
  3     0x00014000      0x000fefff      "second"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   efe25a87-e0ba-401e-8bf6-e81ae29cbc35
  4     0x000ff000      0x001e9fff      "third"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   150f9151-7710-42f4-b819-3b3bd506a2bf

Now I want to duplicate the image in the eMMC so that I end up with 8 partitions like so:
Part    Start LBA       End LBA         Name
        Attributes
        Type GUID
        Partition GUID
  1     0x00000800      0x0000681f      "boot"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   cd5df8ce-ded3-4cf4-b364-33d7a4b24953
  2     0x00006820      0x000139e7      "first"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   3acc4557-2273-462a-a2bd-d130b3a5745d
  3     0x00014000      0x000fefff      "second"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   efe25a87-e0ba-401e-8bf6-e81ae29cbc35
  4     0x000ff000      0x001e9fff      "third"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   150f9151-7710-42f4-b819-3b3bd506a2bf
  5     0x00000800      0x0000681f      "boot"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   cd5df8ce-ded3-4cf4-b364-33d7a4b24953
  6     0x00006820      0x000139e7      "first"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   3acc4557-2273-462a-a2bd-d130b3a5745d
  7     0x00014000      0x000fefff      "second"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   efe25a87-e0ba-401e-8bf6-e81ae29cbc35
  8     0x000ff000      0x001e9fff      "third"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   150f9151-7710-42f4-b819-3b3bd506a2bf

So I write again the same image to eMMC with an offset (to not override the existing one)
=> mmc write 0x600000000 0x200000 0x3FFFFF

MMC write: dev # 1, block # 2097152, count 4194303 ... 4194303 blocks written: OK

However, I don't get the 8 partitions I was expecting but only 4 partitions:
=> mmc rescan
=> mmc part

Partition Map for MMC device 1  --   Partition Type: EFI

Part    Start LBA       End LBA         Name
        Attributes
        Type GUID
        Partition GUID
  1     0x00000800      0x0000681f      "boot"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   cd5df8ce-ded3-4cf4-b364-33d7a4b24953
  2     0x00006820      0x000139e7      "first"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   3acc4557-2273-462a-a2bd-d130b3a5745d
  3     0x00014000      0x000fefff      "second"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   efe25a87-e0ba-401e-8bf6-e81ae29cbc35
  4     0x000ff000      0x001e9fff      "third"
        attrs:  0x0000000000000000
        type:   0fc63daf-8483-4772-8e79-3d69d8477de4
        guid:   150f9151-7710-42f4-b819-3b3bd506a2bf

A: When you write an image that contains one or more partitions, you also write the partition table, which is expected to be at some offset or your memory by u-boot (according to this post it must be 0x60000000). So if you write your image again somewhere else, u-boot will still refer to the partition table from your first writing operation, which itself contains the memory address of your first 4 partitions. Your second partition table is somewhere else on the disk, but u-boot doesn't know.
You can try to repair the partition table using the testdisk command line utility. It will scan the whole disk and hopefully it will find that there is 8 partitions in total, and create a new partition table at 0x60000000 that refers to all of them.


Q: JAXB adding unwanted tags in XML and removing desired ones I'm having the following structure of my classes:
@XmlRootElement(name = "storage")
@XmlType(propOrder = {
        "entries"
})
@XmlAccessorType(XmlAccessType.FIELD)
public class A {
    @XmlElement(name = "configuration")
    private Set<ClassB> entries;
    ...
}

@XmlRootElement(name = "configuration")
@XmlType(propOrder = {
        "name",
        "entries"
})
@XmlAccessorType(XmlAccessType.FIELD)
public class B {
    private String name;
    @XmlElement(name = "configurationEntry")
    private Set<ClassC> entries;
    ...
}

@XmlRootElement(name = "configurationEntry")
@XmlType(propOrder = {
        "property1",
        "property2",
        "property3"
})
@XmlAccessorType(XmlAccessType.FIELD)
public class C {
    private String property1;
    private String property2;
    private String property3;
    ...
}

When I use Jersey to make me an XML out of that, I get the following output when I try to access the root container (Class A). I have no idea why instead of  tags are there  tags.
<Bes>
    <configuration>
        <name>Name1</name>
        <configurationEntry>
            <property1>...</property1>
            <property2>...</property2>
            <property3>...</property2>
        </configurationEntry>
        <configurationEntry>
            <property1>...</property1>
            <property2>...</property2>
            <property3>...</property2>
        </configurationEntry>
    </configuration>
    <configuration>
        <name>Name2</name>
        <configurationEntry>
            <property1>...</property1>
            <property2>...</property2>
            <property3>...</property2>
        </configurationEntry>
        <configurationEntry>
            <property1>...</property1>
            <property2>..</property2>
            <property3>...</property2>
        </configurationEntry>
    </configuration>
</Bes>

When I try to access one of ClassB containers, I get the following. (Similiar issue as previous), instead of  I get  and there is no  tag included.
<Aes>
    <configurationEntry>
        <property1>...</property1>
        <property2>...</property2>
        <property3>...</property2>
    </configurationEntry>
    <configurationEntry>
        <property1>...</property1>
        <property2>...</property2>
        <property3>...</property2>
    </configurationEntry>
<Aes>

The only one that works as expected is the one on the lowest level, Class C
<configurationEntry>
    <property1>...</property1>
    <property2>...</property2>
    <property3>...</property2>
</configurationEntry>

Just to be clear, my desired outputs are as following:
When accessing storages (Class A) container:
<storage>
    <configuration>
        <name>Name1</name>
        <entries>
            <configurationEntry>
                <property1>...</property1>
                <property2>...</property2>
                <property3>...</property2>
            </configurationEntry>
            <configurationEntry>
                <property1>...</property1>
                <property2>...</property2>
                <property3>...</property2>
            </configurationEntry>
        </entries>
    </configuration>
    <configuration>
        <name>Name2</name>
        <entries>
            <configurationEntry>
                <property1>...</property1>
                <property2>...</property2>
                <property3>...</property2>
            </configurationEntry>
            <configurationEntry>
                <property1>...</property1>
                <property2>..</property2>
                <property3>...</property2>
            </configurationEntry>
        </entries>
    </configuration>
</storage>

When accessing 2nd level container, Class B, I would like the following:
<configuration>
    <name>Name1</name>
    <entries>
        <configurationEntry>
            <property1>...</property1>
            <property2>...</property2>
            <property3>...</property2>
        </configurationEntry>
        <configurationEntry>
            <property1>...</property1>
            <property2>...</property2>
            <property3>...</property2>
        </configurationEntry>
    </entries>
</configuration>

Class C is OK with:
<configurationEntry>
    <property1>...</property1>
    <property2>...</property2>
    <property3>...</property2>
</configurationEntry>

A: since i see tag <Bes> and <Aes> in class A and class B.. i feel that you have already defined root element.. i mean class A and Class B are subset of another class.. check this because an xml can have only one root element. if it is so then root element in class A and B is not valid. i don't see any issue with the xml defined in the class. for more information please visit http://java.dzone.com/articles/jaxb-and-root-elements

A: Never mind, I'm an idiot. -.-'
In my client code, for some reason I was retrieving Set<B> and Set<C> instead of A and B, respectively.


Q: Drupal 7, Not sure how to theme my output correctly from query data I’ve been using Views to selectively returned nodes, but right now I want to return my nodes and use the Taxonomy term as a group header. I can't see anyway to get Views to do this for me, other then create multiple views on one page.
So I thought I'd right a module. I've written the SQL to return the correct nodes, but I can't work out how to send them to the themeing engine properly. I would like some advice on how to go about this, my tutorial book has examples of building a list as shown below.
foreach ($result as $row2) {
$items[]  = l($row2->title,'node/'.$row2->nid.'/edit');
}
return array('#markup' => theme('item_list',array('items' => $items)));

now I want to return my nodes attached image file in Teaser mode, and the title of the node, plus (and I dont want to get ahead of myself) I may also want a couple of the addition node fields appended to the title. Should be easy right? I can't work it out at all.
I have wrangled my way around it (a bit) by using what I'm sure is a non drupal method which looks a bit like this, trouble is I can't get my output to work with ColorBox module, so I'm thinking if I can get official Teaser node data out it might work better, and i'd feel better knowing I was doing things in a drupaly way :)
foreach ($result as $row2) {
$items .= 'title.' '.$row2->fielddata.'" alt="'.$row2->title.'" src="http://localhost/theme/sites/default/files/styles/thumbnail/public/field/image/'.$row2->filename .'">';
$items .= '

';
}
return array('#markup' => $items);

Really appreciate any time you take to help me out and thanks in advance.

A: The following code should help. If you don't already have it, install the devel module, it gives you a wonderful function called dpm() which will print the contents of an array/object to the messages area.
// Get some nodes ids
$nids = db_query('SELECT nid FROM {node}')->fetchCol();

// Load up the node objects
$nodes = node_load_multiple($nids);

// This will print the node object out to the messages area so you can inspect it to find the specific fields you're looking for
dpm($nodes);

// I guess you'll want to do something like this:
$terms = array();

foreach ($nodes as $node) {
  // Load the taxonomy term associated with this node. This will be found in a field as this is how taxonomy terms and nodes are related in D7
  $term = taxonomy_term_load($node->field_vocab_name['und'][0]['tid']);

  // Set up the array
  if (!isset($terms[$term->name])) {
    $terms[$term->name] = array();
  }

  // Create some markup for this node
  $markup = '
' . l($node->title . ' ' . $node->field_other_field['und'][0]['value'], "node/$node->nid") . '
';

  // Add an image
  $image = theme('image', array('path' => $node->field_image['und'][0]['uri'], 'alt' => $node->title));
  $markup.= $image;

  // Add the markup for this node to this taxonomy group's list
  $terms[$term->name][] = $markup;
}

// Make up the final page markup
$output = '';
foreach ($terms as $term_name => $node_list) {
  $output .= '
' . check_plain($term_name) . '
';
  $output .= theme('item_list', array('items' => $node_list));
}

return $output;

Hope that helps

A: You can get views to group the returned nodes by the taxonomy term for you. Assuming you are using a field view type, just add the taxonomy field and then where it says Format:Unformatted list | Settings click on Settings at the right hand side and choose your taxonomy field as the grouping field.
Note: if you are not using a field view type, or if you are not using unformatted list then the instructions will be a variation of the above.


Q: Concat variable names in GitLab We use a Gitlab Project in a team. Each developer has his own Kubernetes cluster in the cloud and an own branch within GitLab. We use GitLab-CI to automatically build new containers and deploy them to our Kubernetes clusters.
At the moment we have a .gitlab-ci.yml looks something like this:
variables:
    USERNAME: USERNAME
    CI_K8S_PROJECT: ${USERNAME_CI_K8S_PROJECT}
    REGISTRY_JSON_KEY_FILE: ${USERNAME_REGISTRY_JSON_KEY_FILE}
    [...]

stages:
  - build
  - deploy
  - remove

build-zeppelin:
  stage: build
  image: docker:latest
  variables:
    image_name: "zeppelin"
  only:
    - ${USERNAME}@Gitlab-Repo
  tags:
    - cloudrunner
  script:
    - docker login -u _json_key -p "${REGISTRY_JSON_KEY_FILE?}" https://eu.gcr.io
    - image_name_fqdn="eu.gcr.io/${CI_K8S_PROJECT?}/${image_name?}:latest"
    - docker build -t ${image_name_fqdn?} .
    - docker push ${image_name_fqdn?}
    - echo "Your new image is '${image_name_fqdn?}'. Have fun!"

[...]

So in the beginning we reference the important information by using a USERNAME-prefix. This works quite well, but is problematic, since we need to correct them after every pull request from another user.
So we search for a way to keep the gitlab-ci file the same to every developer while still referencing some gitlab-variables different for every developer.

Things we thought about, that don't seem to work:
Use multiple yml files and import them into each other => not supported.
Try to combine Gitlab Environment variables as Prefix:
CI_K8S_PROJECT: ${${GITLAB_USER_ID}_CI_K8S_PROJECT}

or
INDIVIDUAL_CI_K8S_PROJECT: ${GITLAB_USER_ID}_CI_K8S_PROJECT
CI_K8S_PROJECT: ${INDIVIDUAL_CI_K8S_PROJECT}

A: Solution from @nik will work only for bash. For sh will work:
before_script:
  - variableName=...
  - export wantedValue=$( eval echo \$$variableName )

A: We found a solution using indirect expansion (bash feature):
before_script:
 - variableName=${GITLAB_USER_ID}_CI_K8S_PROJECT
 - export wantedValue=${!variableName}

But we also recognised, that our setup was somehow stupid: It does not make sense to have multiple branches for each user and use prefixed variables, since this leads to problems such as the above and security concerns, since all variables are accessible to all users.
It is way easier if each user forks the root project and simply creates a merge request for new features. This way there is no renaming/prefixing of variables or branches necessary at all.

A: Something like this works (on 15.0.5-ee):
variables:
  IMAGE_NAME: "test-$CI_PROJECT_NAME"


Q: How to navigate from Content Page to Shell in native forms? In my xamarin forms native 3.x project, currently I am navigating from content page to content page using below code
Android.Support.V4.App.Fragment mainPage = new ContentPage().CreateSupportFragment(this);

        SupportFragmentManager
            .BeginTransaction()
            .Replace(Resource.Id.fragment_frame_layout, mainPage)
            .Commit();

Ref:- https://learn.microsoft.com/en-us/xamarin/xamarin-forms/platform/native-forms
But this is not working in case of navigation from content page to Shell (Xamarin Forms 4.0.0).
Any help is appreciated.


Q: TypeError: unorderable types: int() > list() # Import Packages
import random

# Global Variables
perf_num = 500
species = [20]
temp_num = 0
length = 0
s = 0

# Main Program
for num in range(100):
    r1 = int(random.random()*10)
    r2 = int(random.random()*10)
    species.append(r1)
    length = len(species)
    while s < length:
        print(s)
        if species[s-1] > species[s]:
            temp_num = species[s-1] - r1
            species[s-1] = temp_num
        else:
            temp_num = species[s] - r1
            species[s] = temp_num
        if s-1 < 5:
            species[s-1] = []
        s += 1

    print(species)

Please don't explain in very complicated coding language as I just started learning Python from youtube. I tried making my own program and continue to get this error.

A: In the following line:
species[s-1] = []

you're assigning an empty list to a list of numbers, which results in something like:
20 [20, 2] 2

Then when you try to compare a number and a list:
if species[s-1] > species[s]:

you'll get that error:
TypeError: unorderable types: int() > list()


Q: javapos: how to set font size? I'm using javapos 1.15 to print on some epson thermal printer.
All basics feats works properly except one: I don't know how to change the font size (neither type, but that's ok).
According to documentation I could use some escaped caractere but none works. I can make text wider
and bolder but not smaller.
Any help here?
So basically

mPrinter.printNormal(POSPrinterConst.PTR_S_RECEIPT,ESC+"|bC hello"); //That's works
mPrinter.printNormal(POSPrinterConst.PTR_S_RECEIPT,ESC+"|50P hello"); //doesn't works

Thanks in advance
(fyi I print on epson TM-m30 that allow all text size (works fine with and AndroidEpsonSDK))

A: To change the font size (decrease), you need to change the RecLineChars property.
Only the values contained in the RecLineCharsList property can be specified for the RecLineChars property.
It cannot normally be specified in the middle of a PrintNormal print request string.
It may be possible to support it as a vendor-specific feature, but even in that case, it is only possible to change line units, and it is not possible to change only the middle of a line.


Q: Pop up not showing outside when used with resize column by using PrimeNG Table I am using PrimeNG components in Angular 5 project. In my landing I have requirements like resize column and filters(pop up).
Pop up is showing correctly on table without using resize column class  pResizableColumn. But when I use resize column class, pop up is limited to that header column only, rest of the part is hiding that because that pResizableColumn is using position relative.
I want to show pop up with column resize function, if any one know please help me out.
Below Images is the shows clearly.
Popu up showing proper

Pop up hiding when i use resize column

file.html

                                <ng-template pTemplate="colgroup" let-columns>
                                    <colgroup>
                                        <col style="width:30px">
                                        <col style="width:150px">
                                        <col *ngFor="let col of columns" style="width:150px">
                                    </colgroup>
                                </ng-template>
                                <ng-template pTemplate="header" let-columns let-fetchCases>

                                        Ticket Reference

                                            {{col.title}}

                                                    <input class="col-sm-12 inlineInput" type="text" placeholder="Filter...">
                                                    <button class="col-sm-6 btn btn-stable">Search</button>
                                                    <button class="col-sm-6 btn btn-stable">Clear</button>

                                    </ng-template>
                                <ng-template pTemplate="body" let-fetchCases let-columns="columns">

{{fetchCases.ticketRef}}

                                            <div class="extentedNotes" title="{{fetchCases[col.field]}}" [ngClass]="{'timeLeftCol':(col.mapper == 'timeLeft'),
                                                            'rag-status-green':(col.mapper == 'timeLeft' && fetchCases['rag'] == 'Green'),
                                                            'rag-status-red':(col.mapper == 'timeLeft' && fetchCases['rag'] == 'Red'),
                                                            'rag-status-yellow':(col.mapper == 'timeLeft' && fetchCases['rag'] == 'Amber')}">{{fetchCases[col.mapper]}}

                                </ng-template>

 10" [rows]="10" [totalRecords]="totalRecords" [first]="first" (onPageChange)="loadTicketDetailsLazy($event)">

component.ts

opeenFilter(selectedFilter){
    event.stopPropagation()
    if(this.selectedFilter == selectedFilter) {
      this.selectedFilter = "";
    }else {
      this.selectedFilter = selectedFilter;
    }

  }

  hideFilterPopup(){
    if(this.selectedFilter != ""){
      this.selectedFilter = "";
    }
  }

style.css

.inlineFilters {
    position: absolute;
    z-index: 2;
    padding: 5px;
    background: #EFEFEF;
    border-radius: 5px;
    max-width: 15%;
}

.inlineFilters .inlineInput {
    margin-bottom: 5px;
}
.inlineFilters button {
    padding: 0 !important;
}

A: Change the position of the inlineFilters class and replace absolute with fixed :
.inlineFilters {
    position: fixed;
    z-index: 2;
    padding: 5px;
    background: #EFEFEF;
    border-radius: 5px;
    width: 188px;
}


Q: Why does the 'like' count in my page rollback? I'm attempting to implement facebook "likes" and having a bit of trouble.  The count keeps rolling back after a page refresh.
Steps to reproduce

*

*Navigate to http://bookmill.co.kr/books/9/quotations/79  (note: this page is in Korean)

*Click Like

*Notice the like count increments

*Refresh your browsers

Notice that after step #4 the count is rolled back?   The like is posted to my Facebook wall. I'm not clear what's going wrong.
I attempted the same thing with: https://developers.facebook.com/docs/reference/plugins/like/
 and it's rollback too.
Any idea what's going on?  og tag is wrong? incorrect AppId?

A: facebooklikes: Well, developer.facebook has limitation. So you probably need to hire an expert in programming.


Q: Integrating Symfony2 and Redis I am trying to integrate Redis with my Symfony API, I found this bundle : RedisBundle
I installed it and configured so that I can cache Doctrine like so config.yml:
# Doctrine Configuration
doctrine:
    dbal:
        driver:   pdo_mysql
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8

    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true

        metadata_cache_driver: redis
        # enable query caching
        query_cache_driver: redis

snc_redis:
# configure predis as client
clients:
    default:
        type: predis
        alias: default
        dsn: redis://localhost
    doctrine:
        type: predis
        alias: doctrine
        dsn: redis://localhost
# configure doctrine caching
doctrine:
    metadata_cache:
        client: doctrine
        entity_manager: default
        document_manager: default
    result_cache:
        client: doctrine
        entity_manager: [default]
    query_cache:
        client: doctrine
        entity_manager: default

In my FetchBookRepository I am trying to use RedisCache there:
<?php

namespace BooksApi\BookBundle\Repositories;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Query\QueryException;

use Snc\RedisBundle\Doctrine\Cache\RedisCache;
use Predis\Client;

class FetchBookRepository
{
    /**
     * @var EntityManager
     */
    public $em;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(
        EntityManager $entityManager
    ){
        $this->em = $entityManager;
    }

    /**
     * @param $id
     * @return null|object
     * @throws QueryException
     */
    public function fetchBook($id)
    {

        $predis = new RedisCache();
        $predis->setRedis(new Client);
        $cache_lifetime= 3600;

        try {
            $book = $this->em->getRepository('BooksApiBookBundle:BooksEntity')
                ->find($id);

        } catch (\Exception $ex) {
            $this->em->close();
            throw new QueryException('003', 502);
        }

        return $book;
    }
}

I called the RedisCahce and Client classes but how do I now use it with my query..? I cant really find much on Google in regards to Symfony & Redis.
UPDATE:
When I use redis-cli and type in MONITOR i get this output:
1454337749.112055 [0 127.0.0.1:60435] "GET" "[BooksApi\\BookBundle\\Entity\\BooksEntity$CLASSMETADATA][1]"

A: Your Redis config looks OK.
You are using Redis to cache Meatada (Doctrine collected about Entities mappings, etc) and Query (DQL to SQL).
To use Redis as Cache for Results you must write custom Query and define that it is cacheable. Please follow the Doctrine manual http://docs.doctrine-project.org/en/latest/reference/caching.html#result-cache and this GitHub issue https://github.com/snc/SncRedisBundle/issues/77


Q: Android, BottomNavigationView, set weight for each item? I am using Bottom navigation bar in my app. It contains 3 items as in below:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.MainActivity">

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="#ffffff"
    android:layout_weight="9">

    <GridView
        android:id="@+id/gvMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3" />
</FrameLayout>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_gravity="bottom"
    android:layout_weight="1"
    android:background="?android:attr/windowBackground"
    android:backgroundTint="#f5f5f5"
    app:menu="@menu/navigation" />

</LinearLayout>

Here there is the "@menu/navigation" code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item
    android:id="@+id/navigation_home"
    android:icon="@drawable/ic_home_black_24dp"
    android:title="Button1"/>

<item
    android:id="@+id/navigation_dashboard"
    android:icon="@drawable/ic_dashboard_black_24dp"
    android:title="Button2"/>

<item
    android:id="@+id/navigation_notifications"
    android:icon="@drawable/ic_notifications_black_24dp"
    android:title="Button3"/>

</menu>

Now I want to somehow have the middle button take half the space provided and the other two share the other half. But no weight attribute is present. In other words, I want to set the layout weight for the button2 to 2 and for the button1 and button3 to 1. Is there a way to do this?
Any help or tips is appreciated.
Below are the shapes that might help:
Current layout:
Current State
MY goal is to change it like this:
What I want

A: Here is my suggestion:
you can use an layout to replace the menu:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

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

    <FrameLayout
        android:id="@+id/fl_page_home"
        android:layout_width="wrap_content"
        android:layout_height="57dp"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">

        <Button

            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_gravity="center_horizontal"
            android:background="your drawable"
             />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="32dp"
            android:text="your text" />

    </FrameLayout>

     <FrameLayout
        android:id="@+id/fl_page_dashboard"
        android:layout_width="wrap_content"
        android:layout_height="57dp"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">

        <Button

            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_gravity="center_horizontal"
            android:background="your drawable"
             />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="32dp"
            android:text="your text" />

    </FrameLayout>

     <FrameLayout
        android:id="@+id/fl_page_notification"
        android:layout_width="wrap_content"
        android:layout_height="57dp"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">

        <Button

            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_gravity="center_horizontal"
            android:background="your drawable"
             />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="32dp"
            android:text="your text" />

    </FrameLayout>

</LinearLayout>

and height is flexable and you can new a new xml to write this as bottom Navigation and then include to your LinearLayout.
In Java class you can implement onclick listener.


Q: OpenCV with XCode GUI and c++ Is it possible, using only c++ to design an opencv GUI using XCode's Cocoa Framework?

A: You can use this c++ library wxwidgets. Add the path to xcode and it should work fine.


Q: counting occurrence of name in list of namedtuple (the name is in a nested tuple) As the title says, i'm trying to count the occurrence of a name in a list of namedtuples, with the name i'm looking for in a nested tuple.
It is an assignment for school, and a big part of the code is given.
The structure of the list is as follows:
paper = namedtuple( 'paper', ['title', 'authors', 'year', 'doi'] )

for (id, paper_info) in Summaries.iteritems():
    Summaries[id] = paper( *paper_info )

It was easy to get the number of unique titles for each year, since both 'title' and 'year' contain one value, but i can't figure out how to count the number of unique authors per year.
I don't expect you guys to give me the entire code or something, but if you could give me a link to a good tutorial about this subject this would help a lot.
I did google around a lot, but i cant find any helpful information!
I hope i'm not asking too much, first time i ask a question here.
EDIT:
Thanks for the responses so far. This is the code i have now:
authors = [
    auth
    for paper in Summaries.itervalues()
    for auth in paper.authors
    ]

authors

The problem is, i only get a list of all the authors with this code. I want them linked to the year tough, so i can check the amount of unique authors for each year.

A: For keeping track of unique objects, I like using set. A set behaves like a mathematical set in that it can have at most one copy of any given thing in it.
from collections import namedtuple

# by convention, instances of `namedtuple` should be in UpperCamelCase
Paper = namedtuple('paper', ['title', 'authors', 'year', 'doi'])

papers = [
    Paper('On Unicorns', ['J. Atwood', 'J. Spolsky'], 2008, 'foo'),
    Paper('Discourse', ['J. Atwood', 'R. Ward', 'S. Saffron'], 2012, 'bar'),
    Paper('Joel On Software', ['J. Spolsky'], 2000, 'baz')
    ]

authors = set()
for paper in papers:
    authors.update(paper.authors) # "authors = union(authors, paper.authors)"

print(authors)
print(len(authors))

Output:
{'J. Spolsky', 'R. Ward', 'J. Atwood', 'S. Saffron'}
4

More compactly (but also perhaps less readably), you could construct the authors set by doing:
authors = set([author for paper in papers for author in paper.authors])

This may be faster if you have a large volume of data (I haven't checked), since it requires fewer update operations on the set.

A: If you don't want to use embeded type set() and want to understand the logic, use a list and if bifurcation.
If we don't use set() in senshin's code:
# authors = set()
# for paper in papers:
#     authors.update(paper.authors) # "authors = union(authors, paper.authors)"

authors = []
for paper in papers:
    for author in paper.authors:
        if not author in authors:
            authors.append(author)

You can get similar result as senshin's. I hope it helps.


Q: CS50 Why can't my code crack a four digit password? I've encountered a problem in C that held me for the past 6 hours, and after research and studies, I decided to seek for help! Sorry, my English is not my first language and I am a beginner coder.
I am able to crack all passwords that are three digits long. However, it seems like I cannot crack passwords that are four digits long. I've tried my best to make some comprehension and figure out my mistakes in the code, but it seems I cannot do so. Please help!
Also, it would be very nice if there would be more explanations why I cannot crack a four digit long passwords instead of plain solution. Thank you in advance!
#define _XOPEN_SOURCE
#include <stdio.h>
#include <string.h>
#include <cs50.h>
#include <crypt.h>
#include <unistd.h>

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

    if (argc != 2){
        printf("Invalid input\n");
        return 1;
    }

    char* hash = argv[1];
    char code[4];
    char* alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int length = strlen(alphabet);

    for (int a = 0; a <= length; a++)
    {
        code[0] = alphabet[a];
        printf("%s\n", code);
        if (strcmp(crypt(code, "50"), hash) == 0)
        {
            printf("%s\n", code);
            return 0;
        }

        for (int b = 0; b <= length; b++)
        {
            code[1] = alphabet[b];
            //printf("%s\n", code[1]);
            if (strcmp(crypt(code, "50"), hash) == 0)
            {
                printf("%s\n", code);
                return 0;
            }

            for (int c = 0; c <= length; c++)
            {
                code[2] = alphabet[c];
                //printf("%s\n", code[2]);
                if (strcmp(crypt(code, "50"), hash) == 0)
                {
                    printf("%s\n", code);
                    return 0;
                }

                for (int d = 0; d <= length; d++)
                {
                    code[3] = alphabet[d];
                    //printf("%s\n", code[3]);
                    if (strcmp(crypt(code, "50"), hash) == 0)
                    {
                        printf("%s\n", code);
                        return 0;
                    }
                }
            }
        }
    }
}


Q: How to SPLIT cell content into sets of 50000 characters in new columns Google Sheets I have 3 columns A, B & C as shown in the image. Column A contains the search key. The second column B contains names and their respective content in the third column C.
I am filtering rows that contain the text in A1 in B:C and concatenating them. The challenge is that each text in the third column is roughly 40k characters. The filter formula works well so the issue is the character limit. This formula =ArrayFormula(query(C1:C,,100000)) which I have in F1 concatenates more than 50000 characters but I am not how to apply it for my case.
Tried to wrap my formula in E1 inside the query function but it wasn't successful. Like so:
=ArrayFormula(query(CLEAN(CONCATENATE(FILTER(C1:C, B1:B=A1))),,100000)).
I also tried to SPLIT the concatenated result into sets of 50000 characters and put the extras in the next columns but wouldn't manage either. The formula I tried in this case is:
=SPLIT(REGEXREPLACE(CLEAN(CONCATENATE(FILTER(C1:C, B1:B=A1))),".{50000}", "$0,"),",")

The link to the spreadsheet
https://docs.google.com/spreadsheets/d/1rhVSQJBGaPQu6y2WbqkO2_UqzyfCc3_76t4AK3PdF7M/edit?usp=sharing

A: Since cell is limited to 50,000 characters, using CONCATENATE is not possible. Alternative solution is to use Google Apps Script's custom function. The good thing about Apps Script is it can handle millions of string characters.
To create custom function:

*

*Create or open a spreadsheet in Google Sheets.

*Select the menu item Tools > Script editor.

*Delete any code in the script editor and copy and paste the code below.

*At the top, click Save.

To use custom function:

*

*Click the cell where you want to use the function.

*Type an equals sign (=) followed by the function name and any input value — for example, =myFunction(A1) — and press Enter.

*The cell will momentarily display Loading..., then return the result.

Code:
function myFunction(text) {
  var arr = text.flat();
  var newStr = arr.join(' ');
  var slicedStr = stringChop(newStr, 50000);
  return [slicedStr];
}

function stringChop(str, size){
  if (str == null) return [];
    str = String(str);
    size = ~~size;
  return size > 0 ? str.match(new RegExp('.{1,' + size + '}', 'g')) : [str];
}

Example:
Based on your sample spreadsheet, there are 4 rows that matches the criteria of the filter and each cell contains 38,976 characters, which is 155,904 characters in total. Dividing it by 50,000 is 3.12. The ceiling of 3.12 is 4 which means we have 4 columns of data.
Usage:
Paste this in cell E1:
=myFunction(FILTER(C1:C, B1:B=A1))

Output:

Reference:

*

*Custom Function


Q: How would I write a malware detection software? What are the resources I need to go through to fully understand how this works? I've looked up online but all I got are software solutions rather than how the software actually detects them.
I want to be able to detect a malware that's in my computer. Let's say there's a trojan horse in my Computer. How would I write a program to detect it?
I'm a beginner at Information Security.
Thanks in advance.

A: Well most endpoint security products have:
 - an on-demand scanning component.
 - a real-time scanning component.
 - hooks into other areas of the OS to inspect data before "released". E.g. Network layer for network born threats.
 - a detection engine - includes file extractors
 - detection data that can be updated.
 - Run time scanning elements.
There are many layers and components that all need to work together to increase protection.
Here are a few scenarios that would need to be covered by a security product.

*

*Malicious file on disk - static scanning - on-demand.  Maybe the example you have.
A command line/on-demand scanner would enumerate each directory and file based on what was requested to be scanned.  The process would read files and pass streams of data to a detection engine. Depending on the scanning settings configured and exclusions, files would be checked.  The engine can understand/unpack the files to check types.  Most have a file type detection component.  It could just look at the first few bytes of a file as per this - https://linux.die.net/man/5/magic.  Quite basic but it gives you an idea on how you can classify a file type before carrying out more classifications.  It could be as simple as a few check-sums of a file at different offsets.

In the case of your example of a trojan file.  Assuming you are your own virus lab, maybe you have seen the file before, analyzed it an written detection for it as you know it is malicious.  Maybe you can just checksum part of the file and publish this data to you product.  So you have virusdata.dat, in it you might have a checksum and a name for it.  E.g.
123456789, Troj-1
You then have a scanning process, that loads your virus data file at startup and opens the file for scanning.  You scanner checksums the file as per the lab scenario and you get a match with the data file.  You display the name as it was labelled.  This is the most basic example really and not that practical bu hopefully it serves some purpose.  Of course you will see the problem with false positives.
Other aspects of a product include:

*

*A process writing a malicious file to disk - real-time.
In order to "see" file access in real-time and get in that stack you would want a file system filter driver.  A file system mini filter for example on Windows: https://msdn.microsoft.com/en-us/windows/hardware/drivers/ifs/file-system-minifilter-drivers.  This will guarantee that you get access to the file before it's read/written.  You can then scan the file before it's written or read by the process to give you a chance to deny access and alert.  Note in this scenario you are blocking until you come to a decision whether to allow or block the access.  It is for this reason that on-access security products can slow down file I/O.  They typically have a number of scanning threads that a driver can pass work to.  If all threads are busy scanning then you have a bit of an issue.  You need to handle things like zip bombs, etc and bail out before tying up a scanning engine/CPU/Memory etc...

*A browser downloading a malicious file.
You could reply on the on-access scanner preventing a file hitting the disk by the browser process but then the browsers can render scripts before hitting the file system.  As a result you might want to create a component to intercept traffic before the web browser.  There are a few possibilities here.  Do you target specific browsers with plugins or do you go down a level and intercept the traffic with a local proxy process.  Options include hooking the network layer with a Layered Service Provider (LSP) or WFP (https://msdn.microsoft.com/en-us/windows/hardware/drivers/network/windows-filtering-platform-callout-drivers2). Here you can redirect traffic to an in or out of process proxy to examine the traffic.  SSL traffic poses an issue here unless you're going to crack open the pipe again more work.

*Then there is run-time protection, where you don't detect a file with a signature but you apply rules to check behavior.  For example a process that creates a start-up registry location for itself might be treated as suspicious.  Maybe not enough to block the file on it's own but what if the file didn't have a valid signature, the location was the user's temp location.  It's created by AutoIt and doesn't have a file version.  All of these properties can give weight to the decision of if it should be run and these form the proprietary data of the security vendor and are constantly being refined.  Maybe you start detecting applications as suspicious and give the user a warning so they can authorize them.
This is a massively huge topic that touches so many layers.   Hopefully this is the sort of thing you had in mind.

A: Among the literature, "The Art of Computer Virus Research and Defense" from Peter Szor is definitely a "must read".


Q: Salesforce - Eliminate the "Action" column in the support view The support view has the "Action" column. How do you disable it? The end users do not need this column, and it takes up so much space.
See screenshot

A: I've successfully used Adblock plus to remove elements from the view. The action column has a unique class (x-grid3-td-ACTION_COLUMN) so if you add the rule ##td.x-grid3-td-ACTION_COLUMN it should remove the column.


Q: Kendo UI Angular Upload File to Backend as Node.JS I am using Kendo Upload Control to upload files to Node.js backend which used GridFS multer.
Angular
<kendo-upload
  [saveField]="file"
  [withCredentials]="false"
  [saveUrl]="uploadUrl"
  (autoUpload)="false"
  [multiple]="false"
  (select)="selectProfilePic($event)"></kendo-upload>

But the node.js API doesn't pick up the request. I am using [saveField]="file" to pass the uploaded file and the node.js below.
var storage = new GridFsStorage({
    //url: mongoose.connection.client.s.url,
    //options: options,
    db: mongoose.connection,
    file: (req, file) => {
      return new Promise((resolve, reject) => {
        myCrypto.randomBytes(16, (err, buf) => {
          if (err) {
            return reject(err);
          }
          const filename = buf.toString('hex') + path.extname(file.originalname);
          const fileInfo = {
            filename: filename,
            bucketName: 'uploads'
          };
          resolve(fileInfo);
        });
      });
    }
  });

const upload = multer({ storage });
router.post('/upload', upload.single('file'), fileUpload);

module.exports = router;

function fileUpload(req, res) {

 console.log("fileUpload")
  try {
    res.send({ file: req.file })
  }
  catch(err){

    console.log(err);
    res.send(err)
  }
}

Logs

2019-07-21T19:34:33.679205+00:00 app[web.1]: File Controller
  2019-07-21T19:34:33.680436+00:00 app[web.1]: {}
  2019-07-21T19:34:33.983631+00:00 app[web.1]: MulterError: Unexpected
  field 2019-07-21T19:34:33.983647+00:00 app[web.1]: at
  wrappedFileFilter (/app/node_modules/multer/index.js:40:19)
  2019-07-21T19:34:33.983649+00:00 app[web.1]: at Busboy.
  (/app/node_modules/multer/lib/make-middleware.js:114:7)
  2019-07-21T19:34:33.983650+00:00 app[web.1]: at Busboy.emit
  (events.js:198:13) 2019-07-21T19:34:33.983670+00:00 app[web.1]: at
  Busboy.emit (/app/node_modules/busboy/lib/main.js:38:33)
  2019-07-21T19:34:33.983671+00:00 app[web.1]: at PartStream.
  (/app/node_modules/busboy/lib/types/multipart.js:213:13)
  2019-07-21T19:34:33.983673+00:00 app[web.1]: at PartStream.emit
  (events.js:198:13) 2019-07-21T19:34:33.983674+00:00 app[web.1]: at
  HeaderParser. (/app/node_modules/dicer/lib/Dicer.js:51:16)
  2019-07-21T19:34:33.983675+00:00 app[web.1]: at HeaderParser.emit
  (events.js:198:13) 2019-07-21T19:34:33.983677+00:00 app[web.1]: at
  HeaderParser._finish
  (/app/node_modules/dicer/lib/HeaderParser.js:68:8)
  2019-07-21T19:34:33.983678+00:00 app[web.1]: at SBMH.
  (/app/node_modules/dicer/lib/HeaderParser.js:40:12)
  2019-07-21T19:34:33.983679+00:00 app[web.1]: at SBMH.emit
  (events.js:198:13) 2019-07-21T19:34:33.983680+00:00 app[web.1]: at
  SBMH._sbmh_feed (/app/node_modules/streamsearch/lib/sbmh.js:159:14)
  2019-07-21T19:34:33.983682+00:00 app[web.1]: at SBMH.push
  (/app/node_modules/streamsearch/lib/sbmh.js:56:14)
  2019-07-21T19:34:33.983683+00:00 app[web.1]: at HeaderParser.push
  (/app/node_modules/dicer/lib/HeaderParser.js:46:19)
  2019-07-21T19:34:33.983685+00:00 app[web.1]: at Dicer._oninfo
  (/app/node_modules/dicer/lib/Dicer.js:197:25)
  2019-07-21T19:34:33.983686+00:00 app[web.1]: at SBMH.
  (/app/node_modules/dicer/lib/Dicer.js:127:10)
  2019-07-21T19:34:33.989908+00:00 heroku[router]: at=info method=POST
  path="/v1/file/upload" host=herokuapp.com
  request_id=aa1010df-d244-46bc-9b36-f8e437d5ad2a fwd="80.233.46.84"
  dyno=web.1 connect=0ms service=312ms status=500 bytes=286
  protocol=https

A: Is there any chance you had to set the field name to some file variable? So, I believe you expected [saveField]="file" to set field name to 'file' string but instead it searches for some this.filevariable which is undefined so you got field name set to the default 'files' value?

A: Followed @GProst suggestions and analysed a bit and the below fix worked and I don't know the solution yet.
As per the Kendo UI angular documentation,

Sets the FormData key which contains the files submitted to saveUrl.
  The default value is files.

So, I just changed the parameter name from file to files and it worked.
const upload = multer({ storage });
router.post('/upload', upload.single('files'), fileUpload);


Q: UITextView is partially scrolled down when view opened I create a UITextView and add a lot of text to it. When I launch the view, the UITextView is always partially scrolled down. Of cause the user can scroll up, but it just feels weird.
What happens? Did I miss any obvious settings?
Please refer to the following image. Part of text is cut out. I borrow the text from link.

I started a simple Single View Application. This is how my viewDidLoad looks like:
- (void)viewDidLoad {
    [super viewDidLoad];

    NSString* path = [[NSBundle mainBundle] pathForResource:@"license"
                                                     ofType:@"txt"];
    NSString* terms = [NSString stringWithContentsOfFile:path
                                                encoding:NSUTF8StringEncoding
                                                   error:nil];
    self.textField.text = terms;
}

And this is my storyboard:

This is how it looks after manually scroll up to the top.

A: Add this line at the end of your viewDidLoad:
[self.textField scrollRangeToVisible:NSMakeRange(0, 1)];

Like this:
- (void)viewDidLoad {
    [super viewDidLoad];

    NSString* path = [[NSBundle mainBundle] pathForResource:@"license"
                                                     ofType:@"txt"];
    NSString* terms = [NSString stringWithContentsOfFile:path
                                                encoding:NSUTF8StringEncoding
                                                   error:nil];
    self.textField.text = terms;
    [self.textField scrollRangeToVisible:NSMakeRange(0, 1)];
}

A: This used to happens on all iPhone/iPod devices under landscape mode, and solutions by the others will work. Now it only happens for iPhone 6+ or iPhone 6s+ under landscape mode. This is a work around for it:
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.textView scrollRangeToVisible:NSMakeRange(0, 1)];
    });
}

The view is scrolled somehow after the viewWillAppear and before viewDidAppear, and that's why we need the dispatch above.

A: I had the same problem and I solved it by getting the previous scroll position and reseting it after updating the "text"
CGPoint p = [self.texField contentOffset];
self.textField.text = terms;
[self.textField setContentOffset:p animated:NO];
[self.textField scrollRangeToVisible:NSMakeRange([tv.text length], 0)];

A: For those using Xamarin, this is the only solution that works for me:
textView.Text = "very long text";

DispatchQueue.MainQueue.DispatchAsync(() =>
{
    textView.ContentOffset = new CGPoint(0, 0);
});

A: The best working solution for me (Objective C):
- (void)viewDidLayoutSubviews {
     [self.myTextView setContentOffset:CGPointZero animated:NO];
}


Q: Using StepVerifier in a parallel testing environment I am having some trouble when using StepVerifier's withVirtualTime and create methods in a parallel testing environment.
private static final Duration DELAY = Duration.ofSeconds(1);

public void testA() {
    StepVerifier.withVirtualTime(() -> Mono.just(1).delayElement(DELAY))
            .thenAwait(DELAY)
            .expectNext(1)
            .expectComplete()
            .verify();
}

public void testB() {
    StepVerifier.create(Mono.just(1).delayElement(DELAY))
            .thenAwait(DELAY)
            .expectNext(1)
            .expectComplete()
            .verify();
}

Maven Surefire plugin configuration:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.2</version>
    <configuration>
        <groups>unit</groups>
        <includes>
            <include>**/*Test.java</include>
        </includes>
        <parallel>methods</parallel>
        <threadCount>2</threadCount>
        <trimStackTrace>false</trimStackTrace>
    </configuration>
</plugin>

These tests fail with the following exceptions (The full stack traces available on GitHub, please refer links below.):
[ERROR] testA(com.github.hisener.StepVerifierTest)  Time elapsed: 0.04 s  <<< FAILURE!
java.lang.NullPointerException: timedScheduler
    at java.base/java.util.Objects.requireNonNull(Objects.java:246)
[ERROR] testB(com.github.hisener.StepVerifierTest)  Time elapsed: 0.043 s  <<< FAILURE!
reactor.core.Exceptions$ReactorRejectedExecutionException: Scheduler unavailable
    at reactor.core.Exceptions.failWithRejected(Exceptions.java:249)

I don't think it's related to delayElements, for instance, one of the following tests uses timeout and they also fail:
public void testA() {
    StepVerifier.withVirtualTime(() -> Mono.just(1)).expectNext(1).expectComplete().verify();
}

public void testB() {
    StepVerifier.create(Mono.just(1).timeout(DELAY)).expectNext(1).expectComplete().verify();
}

I have tested on both TestNG and Junit 5, but no luck. The code is available on GitHub:

*

*TestNG https://github.com/hisener/reactor-test-test

*JUnit 5 https://github.com/hisener/reactor-test-test/tree/junit5

A: StepVerifier#withVirtualTime replaces ALL default Schedulers with the virtual time one, so it is not a good idea to use it in parallel


Q: C# item Drag Fix I move three controls using this code on MouseMove Event :
if (inHareket)
{
    GelenResimcik.Left = e.X + GelenResimcik.Left -MouseDownLocation.X;
    GelenResimcik.Top = e.Y + GelenResimcik.Top - MouseDownLocation.Y;
    GelenResimcik.BackColor = Color.Transparent;
    ResimHareket.Left = e.X + ResimHareket.Left - MouseDownLocation.X;
    ResimHareket.Top = e.Y + ResimHareket.Top - MouseDownLocation.Y;
    Yonlendir.Left = e.X + Yonlendir.Left - MouseDownLocation.X;
    Yonlendir.Top = e.Y + Yonlendir.Top - MouseDownLocation.Y;

    Aktar.Left = e.X + Aktar.Left - MouseDownLocation.X;
    Aktar.Top = e.Y + Aktar.Top - MouseDownLocation.Y;

    Vazgec.Left = e.X + Vazgec.Left - MouseDownLocation.X;
    Vazgec.Top = e.Y + Vazgec.Top - MouseDownLocation.Y;
}

and if I try move them faster the result is :
Notice : When i stop moving, the glow is not visible, it is only moving faster.
What shall I do?
EDIT :
My Controls
this.Yonlendir = new System.Windows.Forms.PictureBox();
this.Vazgec = new System.Windows.Forms.PictureBox();
this.Aktar = new System.Windows.Forms.PictureBox();
this.ResimHareket = new System.Windows.Forms.PictureBox();
this.GelenResimcik = new System.Windows.Forms.PictureBox();

My Init :
        ((System.ComponentModel.ISupportInitialize)(this.Yonlendir)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.Vazgec)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.Aktar)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.ResimHareket)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.GelenResimcik)).BeginInit();
            this.SuspendLayout();
  //
            // Yonlendir
            //
            this.Yonlendir.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
            this.Yonlendir.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.Yonlendir.Image = global::Surface.Properties.Resources.rotate;
            this.Yonlendir.Location = new System.Drawing.Point(26, 74);
            this.Yonlendir.Name = "Yonlendir";
            this.Yonlendir.Padding = new System.Windows.Forms.Padding(5);
            this.Yonlendir.Size = new System.Drawing.Size(30, 30);
            this.Yonlendir.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.Yonlendir.TabIndex = 14;
            this.Yonlendir.TabStop = false;
            this.Yonlendir.Click += new System.EventHandler(this.Yonlendir_Click);
            //
            // Vazgec
            //
            this.Vazgec.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
            this.Vazgec.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.Vazgec.Image = global::Surface.Properties.Resources.iptal;
            this.Vazgec.Location = new System.Drawing.Point(93, 8);
            this.Vazgec.Name = "Vazgec";
            this.Vazgec.Padding = new System.Windows.Forms.Padding(5);
            this.Vazgec.Size = new System.Drawing.Size(30, 30);
            this.Vazgec.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.Vazgec.TabIndex = 13;
            this.Vazgec.TabStop = false;
            this.Vazgec.Click += new System.EventHandler(this.buton1_Click);
            //
            // Aktar
            //
            this.Aktar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
            this.Aktar.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.Aktar.Image = global::Surface.Properties.Resources.kaydet;
            this.Aktar.Location = new System.Drawing.Point(57, 8);
            this.Aktar.Name = "Aktar";
            this.Aktar.Padding = new System.Windows.Forms.Padding(5);
            this.Aktar.Size = new System.Drawing.Size(30, 30);
            this.Aktar.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.Aktar.TabIndex = 12;
            this.Aktar.TabStop = false;
            this.Aktar.Click += new System.EventHandler(this.Onayla_Click);
            //
            // ResimHareket
            //
            this.ResimHareket.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40)))));
            this.ResimHareket.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.ResimHareket.Image = global::Surface.Properties.Resources.hareket;
            this.ResimHareket.Location = new System.Drawing.Point(26, 38);
            this.ResimHareket.Name = "ResimHareket";
            this.ResimHareket.Padding = new System.Windows.Forms.Padding(5);
            this.ResimHareket.Size = new System.Drawing.Size(30, 30);
            this.ResimHareket.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.ResimHareket.TabIndex = 11;
            this.ResimHareket.TabStop = false;
            this.ResimHareket.Click += new System.EventHandler(this.ResimHareket_Click);
            this.ResimHareket.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ResmiHareket_MouseDown);
            this.ResimHareket.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ResmiHareket_MouseMove);
            this.ResimHareket.MouseUp += new System.Windows.Forms.MouseEventHandler(this.ResimHareket_MouseUp);
            //
            // GelenResimcik
            //
            this.GelenResimcik.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
            this.GelenResimcik.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            this.GelenResimcik.Location = new System.Drawing.Point(57, 39);
            this.GelenResimcik.Name = "GelenResimcik";
            this.GelenResimcik.Size = new System.Drawing.Size(438, 452);
            this.GelenResimcik.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.GelenResimcik.TabIndex = 2;
            this.GelenResimcik.TabStop = false;

My Timer (Interval 100):
  private void ResimKontrol_Tick(object sender, EventArgs e)
        {
            try
            {
                if (ontanimli.Height != 0)
                {
                    GelenResimcik.Image = ontanimliGelen;
                    GelenResimcik.Parent = cizim;
                    entegreGoster();

                  }
            }
            catch
            {

            }

        }

entegreGoster and entegreGizle
public void entegreGoster() { GelenResimcik.BringToFront();ResimHareket.BringToFront();Aktar.BringToFront();Vazgec.BringToFront(); Yonlendir.BringToFront(); }
        public void entegreGizle() { GelenResimcik.SendToBack(); ResimHareket.SendToBack(); Aktar.SendToBack(); Vazgec.SendToBack(); Yonlendir.SendToBack(); }

My MouseDown event :
 private void ResmiHareket_MouseDown(object sender, MouseEventArgs e)
        {
            MouseDownLocation = e.Location;
            inHareket = true;
        }

I start timer when Open new form
Ontanimlilar ontanimli = new Ontanimlilar();
            ontanimli.Show();
            ResimKontrol.Start();

ontanimliGelen (public static pictureBox)
ontanimli  Class :
Ciz.ontanimliGelen = seciliRes.Image;
this.Close();


Q: Insert Element between each List element Is there a better way to insert an Element between each pair of elements into a List in Java than iterating through it
List<Integer> exampleInts = new ArrayList<>(Arrays.asList(1,2,3,5,8,13,21));

for (int i = 1; i < exampleInts.size(); i++) {
    int delimiter = 0;
    exampleInts.add(i, delimiter);
    i++;
}

A: No, there is no ready utils for this in standard java libraries.
BTW, your loop is incorrect and will work infinitely until memory end. You should increment i variable one more time:
    for (int i = 1; i < exampleInts.size(); i++) {
        int delimiter = 0;
        exampleInts.add(i, delimiter);
        i++;
    }

or change loop conditions to for (int i = 1; i < exampleInts.size(); i+=2) {

A: Try this solution it is working correctly.
List<Integer> exampleInts = new ArrayList<>(Arrays.asList(1, 2, 3, 5,
            8, 13, 21));
    int size = (exampleInts.size()-1)*2;
    for (int i = 0; i < size; i+=2) {
        int delimiter = 0;
        exampleInts.add(i+1, delimiter);
    }
    System.out.println(exampleInts);


Q: Displaying XML in JSF I have a method that gives back a formatted XML string. I want to show that on a JSF page in a nicely wrapped, readable way. I used this solution first.

<h:outputText value="myBean.xml"/>

The result is indented, but it doesn't wrap very long lines (with a lot of attributes for e.g.)
RichFaces is also available in my project. What would you suggest?
Thanks in advance,
Daniel

A: Not sure if I understand you right, but if it is a plain vanilla String with XML data which you want to display as-is in the JSF page, then the first logical step would be to escape the HTML entities so that it's not been parsed as HTML. You can use h:outputText for this, it by default escapes HTML entities (which is controllable by the 'escape' attribute by the way):
<h:outputText value="#{bean.xmlString}" />

Or if it is formatted and you want to preserve the formatting, then apply the CSS white-space:pre property on the parent HTML element.
Or if you want to add syntax highlighting (colors and so on), then consider a Javascript library which does the task. Googling "javascript xml syntax highlighting" should yield enough results.


Q: Understanding the slicing syntax in Numpy? I have an x dimensional matrix in Numpy.  For this example, I will use a 2x2 array.
np.array([[2, 2], [3,3]])

How would I alternate adding a row and column of some value so the result would look like:
array([[2, x, 3, x],
       [x, x, x, x].
       [2, x, 3, x],
       [x, x, x, x]])

This answer gives a helpful start by saying to set rows in a correctly-sized destination matrix b from a matrix a like so a[::2] = b but what does the ::2 do in the slicing syntax and how can I make it work on columns?
In short what do the x y and z parameters do in the following: a[x:y:z]?

A: If I understand what you want correctly, this should work:
import numpy as np
a = np.array([[2,2],[3,3]])
b = np.zeros((len(a)*2,len(a)*2))
b[::2,::2]=a

This 'inserts' the values from your array (here called a) into every 2nd row and every 2nd column
Edit:
based on your recent edits, I hope this addition will help:
x:y:z means you start from element x and go all the way to y (not including y itself) using z as a stride (e.g. 2, so every 2 elements, so x, x+2, x+4 etc up to x+2n that is the closest to y possible)
so ::z would mean ALL elements with stride z (or ::2 for every 2nd element, starting from 0)
You do that for each 'dimension' of your array, so for 2d you'd have [::z1,::z2] for going through your entire data, striding z1 on the rows and z2 on the columns.
If that is still unclear, please specify what is not clear in a comment.
One final clarification - when you type only : you implicitly tell python 0:len(array) and the same holds for ::z which implies 0:len(array):z.
and if you just type :: it appears to imply the same as : (though I haven't delved deep into this specific example)


Q: Is there a easy way to filter mulitfield in django's admin site? The Model:
class Person(Model):
  (...)
   fathers = models.ManyToManyField('Person', related_name="fathers_children",  blank=True)
   mothers = models.ManyToManyField('Person', related_name="fathers_children",  blank=True)
   sex = models.CharField(null=True, blank=True, max_length=1)

admin.py:
class PersonAdmin(admin.ModelAdmin):
  form = PersonAdminForm
  model = Person

  fields = ('last_name', 'birth_date','fathers','mothers')
  ordering = ['last_name','birth_date']

admin.site.register(Person, PersonAdmin)

(maybe I cut to much, but I think it is self descriptive)
Please don't think why person can have more than one father/mother - it is intentional.
And now when I enter to e.g /admin/person/836, got the form with two MultipleChoiceFields containing full list of persons.
I want to reduce both - fathers should contains males, mothers - females. But how to do it?

A: You can simply limit the queryset for those fields by overriding the init method in the PersonAdminForm class:
class PersonAdminForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(PersonAdminForm, self).__init__(*args, **kwargs)
        self.fields['fathers'].queryset = Person.objects.filter(sex='m')
        self.fields['mothers'].queryset = Person.objects.filter(sex='f')


Q: Adjusting of php.ini I know that it is possible to set parameters in php.ini like this:
error_log = "%sprogdir%/userdata/logs/%phpdriver%_error.log"

How can I properly run php using command line and set these parameters? Similarly:
php -c path/to/php/ini [here something like this: %sprogdir%=path1 %phpdriver%=path2]

A: Are you looking to be able to export a parameter to environment variables using PHP? If so, the exec command may be what you're looking for: PHP: exec - Manual.
You'd execute something similar to this I believe:
<?php
    echo exec('export phpdriver=value');
?>

EDIT: Due to misunderstanding of the question.
To correctly answer the question, we are going to create a script to set some environment variables before executing some PHP from the command line.
Here is our example shell - php_runner.sh
#!/bin/bash
export progsdir=$1
export phpdriver=$2
php -c path/to/php/ini

Once this is created (remember to set correct permissions as well), we can execute it from command line as such:
/path/to/php_runner.sh path1 path2


Q: Dismatched image texture with geometry I have created a planegeometry and a texture which is made by ImageUtils with CanvasRenderer,
and then I created a mesh and finished all relative parameters'settings. The result is that a PlaneGeometry with the image
 texture in the space,but  a diagonal line is showed up,what's more, one image are divided into two
parts by this diagonal line,thus images on this two parts become dismatched.How should I resolve it? The key code are as follows:
    var planeGeo=new THREE.PlaneGeometry(2000,3000);
    var map = THREE.ImageUtils.loadTexture( 'images/greenLines.png' );
    map.wrapS=map.wrapT = THREE.RepeatWrapping;
    map.repeat.set(2,2);
    map.anisotropy = 16;
    var planeMaterial=new THREE.MeshBasicMaterial({color:0xFFBBEE,map:map,overdraw:true});
    var planeMesh=new THREE.Mesh(planeGeo,planeMaterial);
    planeMesh.position.set(2000,-2000,5000);
    scene.add(planeMesh);

NOTICE:the images are constructed by green lines.The result displays that lines are cut and one
line has become two lines which are located on two divided triangles .
Now how should I modify my code so that the two parts of  this image looks matched well without displacement!
Can the diagonal line be removed?


Q: Window in tkinter automatically closes I have some code here that I copied from the tkinter tutorials so I am sure it is 100% correct:
import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = "Hello World\n(click me)"
        self.hi_there["command"] = self.say_hi
        self.hi_there.pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",
                              command=self.master.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print("hi there, everyone!")

root = tk.Tk()
app = Application(master=root)
app.mainloop()

It is supposed to work but instead, when I run the program it shows the window for about 1 millisecond and then closes immediately. How do I fix this?
I am using Python 3.8.

A: mainloop() should be called on a tk.Tk object but in your code app is a tk.Frame object.  So, try ...
root.mainloop()


Q: Compare two files in two different folders and replace it by the newer With this VBScript code I was able to copy files. If the file exists it does nothing, if not it will copy the files needed.
Dim Photo
SourceFolder = "C:\Photo1"
DistinationFolder = "C:\Photo2"
Set ObjPhoto = CreateObject("Scripting.FileSystemObject")

For Each Photo In ObjPhoto.GetFolder( SourceFolder).Files
    If Not ObjPhoto.FileExists(ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp"))) Then
        photo.Copy ObjPhoto.BuildPath(DistinationFolder, Photo.Name), True
    End If
Next

I want to compare the files if the source files also exists in the destination folder and replace it by the newer.

A: If you want to overwrite based on the last modified date, then the File object has the property you want: DateLastModified. (You can check all properties of the File object here.)
You already have access to the source file objects (your code's Photo variable) so you just need to get the target's file object.
Something like this should work:
Dim Photo
Dim targetFile, bmpTargetFilename, jpgTargetFilename

SourceFolder = "C:\Photo1"
DistinationFolder = "C:\Photo2"

Set ObjPhoto = CreateObject("Scripting.FileSystemObject")

For Each Photo In ObjPhoto.GetFolder(SourceFolder).Files
    bmpTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp"))
    jpgTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Photo.Name)

    If ObjPhoto.FileExists(bmpTargetFilename) Then
        ' Get the target file object
        Set targetFile = ObjPhoto.GetFile(jpgTargetFilename)
        ' Now compare the last modified dates of both files
        If Photo.DateLastModified > targetFile.DateLastModified Then
            Photo.Copy jpgTargetFilename, True
        End If
    Else
        Photo.Copy jpgTargetFilename, True
    End If
Next

A couple of notes:

*

*It seems you are checking for the existence of a .BMP file yet copying a .JPG file, so I made it explicit by using two variables.

*I am also assuming you want to compare the JPG files, since those are the ones being copied.


Q: using cURL to retrieve JSON data for use with jQuery I've been reading this helpful post:
http://techslides.com/hacking-the-google-trends-api
It shows how you can use cURL in command line/terminal to request data from google trends, for example;
curl --data "ajax=1&cid=actors&geo=US&date=201310" http://www.google.com/trends/topcharts/trendingchart

Gives you a big block of what I think is JSON. Below is an example of what I am doing to use cURL within my PHP to get data like this- however I cannot find anything that would get the data from the above cURL command to work in PHP like below.
<?php
    //initialize session
    $url = "http://www.google.com/trends/hottrends/atom/feed?pn=p1";
    $ch = curl_init();
    //set options
    curl_setopt($ch, CURLOPT_URL, $url);
    //execute session
    $data = curl_exec($ch);
    echo $data;
    //close session
    curl_close($ch);
    ?>

How do I go about getting the data from above?

A: You can do the same with the PHP cURL extension. You just need to set the options through curl_setopt, so you would do something like this
$url = "http://www.google.com/trends/topcharts/trendingchart";
$fields = "ajax=1&cid=actors&geo=US&date=201310";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

Now you have the response of the website in $data and you can do whatever you want with it.
You can find the PHP cURL documentation on http://php.net/curl

A: Try this
// Complete url with paramters
$url = "http://www.google.com/trends/topcharts/trendingchart?ajax=1&cid=actors&geo=US&date=201310";

// Init session
$ch = curl_init();

// Set options
curl_setopt($ch, CURLOPT_URL, $url);

// Set option to return the result instead of echoing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Execute session
$data = curl_exec($ch);

// Close session
curl_close($ch);

// Dump json decoded result
var_dump(json_decode($data, true));


Q: How to prevent a click on the underlying element? How to prevent a click on the underlying element? When I hover the mouse over the board on the website https://08ce2429.my-trello-frontend.pages.dev/ - the label "Delete board" appears, when I click on it, the board is deleted, but the board page also opens. How to prevent this?
My code of the board element:
  return (
    <div key={props.id} className={`board-home id${props.id}`}>
      <Link
        className="board-link"
        to={{ pathname: '/board/' + props.id }}
        state={{ id: props.id }}
      >

{props.title}

 {
              try {
                e.stopPropagation()
                alert('stopPropagation')
              } catch (err) {
                alert(err)
              }
              //  (document.querySelector(`.id${props.id}`) as HTMLElement).style.pointerEvents = "none"
              deleteBoard((e.target as HTMLElement).getAttribute('id')!)
            }}
          >
            Delete board

      </Link>
      <Routes>
        <Route path="/board/:id" element={<Board />} />
      </Routes>

  )

stopPropagation() does not help.

A: Just use e.preventDefault() in onClick


Q: Why is it possible to set a value in a slice using reflection? According to The Laws of Reflection it is not possible to set the value of an element as follows, you need to use its address.
This will not work:
var x float64 = 3.4
v := reflect.ValueOf(x)
v.SetFloat(7.1) // Error: will panic.

This will work:
var x float64 = 3.4
p := reflect.ValueOf(&x) // Note: take the address of x.
p.Elem().SetFloat(7.1)

So why will the following work when using slices?
floats := []float64{3}

v := reflect.ValueOf(floats)
e := v.Index(0)
e.SetFloat(6)
fmt.Println(floats) // prints [6]

http://play.golang.org/p/BWLuq-3m85
Surely v.Index(0) is taking the value instead of address from slice floats, thus meaning it shouldn't be settable like the first example.

A: In your first example, you pass the actual x. This will copy x and give it to reflect.ValueOf. When you try to do v.SetFloat, as it get only a copy, it has no way to change the original x variable.
In your second example, you pass the address of x, so you can access the original variable by dereferencing it.
In the third example, you pass floats to reflect.ValueOf, which is a slice. "Slice hold references to the underlying array" (http://golang.org/doc/effective_go.html#slices). Which mean that through the slice, you actually have a reference to the underlying object. You won't be able to change the slice itself (append & co) but you can change what the slice refers to.