text:
Q: Discord.Py bot will receive messages but doesn't respond Discord.Py bot will receive messages but doesn't respond
Here is my code:
import discord
import os
from discord.ext import commands

intents = discord.Intents.default()
client = discord.Client(intents=intents)

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    content = message.content
    user = message.author

    if user == client.user:
        return

    print("Received a message:", content)

    if content.strip() == "$hello":
        await message.channel.send("Hi!")

    if content.strip() == "$die":
        await message.channel.send("No you")
        client.close()

client.run(os.environ['Token'])

I have tried multiple different forms of code, none of which worked.

A: You need the message_content intent to access the content of messages; to enable this, you need to enable the intent by going to:

the developer portal > select the bot > "Bot" section > enable the "message content" intent

Then you need to enable it in the code too to tell the Discord API that your bot needs to use it.
intents = discord.Intents.default()
intents.message_content = True # set the "message_content" intent to "True"

client = discord.Client(intents=intents)


text:
Q: How can I optimize this Query with Rails I have an array of book ids and I need to iterate each and save the number of comments for each in a Hash (@book_comments) that will have the book_id as the key and the number of comments for that book as a value. Book has many comments, comment belong to books.
@book_ids.map {|id| @book_comments[id] = Book.find(id).comments.size}

This will hit the DB with these two queries for the amount of ids I have on my array.
SELECT `books`.* FROM `books` WHERE `books`.`id` = ? LIMIT 1
SELECT COUNT(*) FROM `comments` WHERE `comments`.`book_id` = ?

Surely there's a better way.
If you know, please teach me.
Thank you.

A: This should get your hash:
@book_comments = Comment.where(book_id: @book_ids).group(:book_id).count

A: Use this code:
comment_counts_by_book = Book.select('books.id, count(comments.id) as comments_count').
    joins('left outer join comments on comments.book_id = books.id').
    group('books.id').inject({}) { |h, book| h[book.id] = book.comments_count; h }

comment_counts_by_book
# => {1=>2, 2=>5, ...}

It does a single database query returning Book objects with only :id and :comments_count attributes filled out. The result is then transformed using inject to a hash with book ids as keys and comments counts as values.

A: If you're using Rails 4 you can do the following as well:
Comment.eager_load(:book).group(:book).count

It'll generate something like this:
=> #{1=>2, 2=>4, 3=>9}

A: Does this work for you? I'm not sure if I understood the question correctly. Let me know.
Book.find(@book_ids).map(&:comments).size

Update
Is this closer to what you want?
@book_ids.map do |id|
  {
    id => Book.find(id).map(&:comments).size
  }
end

Try this, too
{}.tap do |hash|
  @book_ids.each do |book_id|
    hash[book_id] = Book.find(book_id).map(&:comments).size
  end
end

A: You should use includes to eager load the comments then iterate over that query.
books = Book.where(id: @book_ids).includes(:comments)

books.each do |book|
  @book_comments[book.id] = book.comments.length
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display section-container I'm new to Foundation 4 and am currently trying to do the following:
I'm using the section-container horizontal-nav and was wondering if anyone knows the configuration to get the section container to display its content first by default instead of hiding it until it's been clicked?  So when the page loads, the section will be shown first until the user clicks on "Section 1".

    Section 1

Link 1

Link 2

Link 3

Link 1

A: Tried adding active into the class attribute?

A:
The section is placed as a horizontal nav-bar and I'd like for it to
  be shown when the page loads as if the user has already clicked on it.

You can achieve this by giving you menu items an id and open that menu in jquery.
Section 1

then add this to the script section of your page:
$(function () {
    $("#menu1").click();
});


text:
Q: Why does Gson add slashes to String I implemented a simple HttpServlet. The servlet takes requests and calls a third party API to get the data, and then sends data back in response. However, in the response, JSON adds too many slashes.
Does anyone know why?
Below is my code.
public class InstitutionServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Gson gson = new Gson();

        String city = request.getParameter("city");
        String apiUrl = "https://inventory.data.gov/api/action/datastore_search?resource_id=38625c3d-5388-4c16-a30f-d105432553a4&q=" + city;
        String data = getInstitutions(apiUrl);

        response.setContentType("application/json");
        PrintWriter pw = response.getWriter();
        gson.toJson(data, pw);
    }

    //Get institutions data from API url.
    private String getInstitutions(String apiUrl) {
        StringBuilder institutions = new StringBuilder();

        try {
            URL url = new URL(apiUrl);
            URLConnection urlConnection = url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;

            while ((line = bufferedReader.readLine()) != null) {
                institutions.append(line).append("\n");
            }

            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return institutions.toString();
    }
}

Original data from the API https://inventory.data.gov/api/action/datastore_search?resource_id=38625c3d-5388-4c16-a30f-d105432553a4&q=whatever:
{
    "help": "https://inventory.data.gov/api/3/action/help_show?name=datastore_search",
    "success": true,
    "result": {
        "resource_id": "38625c3d-5388-4c16-a30f-d105432553a4",
        "q": "whatever",
        "records": [],
        "_links": {
            "start": "/api/action/datastore_search?q=whatever&resource_id=38625c3d-5388-4c16-a30f-d105432553a4",
            "next": "/api/action/datastore_search?q=whatever&offset=100&resource_id=38625c3d-5388-4c16-a30f-d105432553a4"
        }
    }
}

Data in servlet response http://localhost:8080/getInstitutions?city=wahtever:
"{\"help\":
  \"https://inventory.data.gov/api/3/action/help_show?name\u003ddatastore_search\",
  \"success\": true,
  \"result\": {
    \"resource_id\": \"38625c3d-5388-4c16-a30f-d105432553a4\",
    \"q\": \"wahtever\",
    \"records\": [],
    \"_links\": {
      \"start\": \"/api/action/datastore_search?q\u003dwahtever\u0026resource_id\u003d38625c3d-5388-4c16-a30f-d105432553a4\",
      \"next\": \"/api/action/datastore_search?q\u003dwahtever\u0026offset\u003d100\u0026resource_id\u003d38625c3d-5388-4c16-a30f-d105432553a4\"
    }
  }
}\n"

A: gson.toJson(data, pw) is taking the string data and converting it to JSON, so to do that, it'll escape all characters it needs to in order to create a valid JSON string.
It's not really clear why you need Gson for this scenario, you should be able to write out data to the PrintWriter directly  assuming that the other function there is already returning a string in JSON format.


text:
Q: Espresso doesn't work with NineOldAndroids animation? I'm trying to test my activity (HomeActivity) which has repeating animation based on NineOldAndroids lib with Espresso. I turned off system animation as described here, but it doesn't help and I'm getting an error (see below). The only thing that help is to remove animation manually.
So question is do I need to manually turn off animations (using BuildConfig seems hassle free) or maybe I'm doing something wrong?
Thank you in advance!
 java.lang.RuntimeException: Could not launch intent Intent {
 act=android.intent.action.MAIN flg=0x14000000
 cmp=com.package.en/com.package.ui.HomeActivity } within 45 seconds.
 Perhaps the main thread has not gone idle within a reasonable amount
 of time? There could be an animation or something constantly
 repainting the screen. Or the activity is doing network calls on
 creation? See the threaddump logs. For your reference the last time
 the event queue was idle before your activity launch request was
 1392052899081 and and now the last time the queue went idle was:
 1392052899081. If these numbers are the same your activity might be hogging the event
 queue.

A: Fix for issue:

    @Before
    public void setUp() throws Exception {
        super.setUp();
        injectInstrumentation(InstrumentationRegistry.getInstrumentation());
        Intent intent = getIntent();
        if (intent == null) {
            intent = new Intent();
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        setActivityIntent(intent);
    }

    @SuppressLint("NewApi")
    @Override
    public T getActivity() {
        final T activity = super.getActivity();
        activity.overridePendingTransition(0, 0);
        return activity;
    }

A: I don't know much about 9olddroids, but for Espresso you should disable animations in order to your tests become reliable, which you probably already did.
So maybe this is the case to increase your app "testability" by adding some code which disable animations. For instance, your activity could have a method to disable animations, like:
 public void disableAnimations() {
     this.mAnimationsEnabled = false;
 }

And before every animation, you check if they're enabled. Once your test begins, you disable your animations:
 public void setUp () {
    super.setUp();
     YourActivity activity = getActivity();
     activity.disableAnimations();
 }

 public void testXYZ() {
     // your test code
 }

I hope this will work, as 9OldDroids will stop interfering with Espresso


text:
Q: Why is it "lay still" instead of "lie still" in this scene in Wonderwoman? https://getyarn.io/yarn-clip/91b8b6ce-5a99-4bae-983d-2585944b7834
This is from Wonder Woman, and a woman on the left is laying the wounded woman down on the grass.

She says to the hurt woman, "lay still."

I don't understand why it's "lay still" instead of "lie still".
I already googled the difference between "lie" and "lay" and lay is a transitive verb which needs an object. It also doesn't make sense if lay here was used as a past form of "lie", since in this scene, the woman is ordering(not exactly ordering in the sense of forcing someone) the wounded woman to lie down still and thus present verb should be used.
What am I missing? Why is it "lay"?

A: Because the movie is wrong; you are correct: "Lie still."
This article from Merriam-Webster supports your correct understanding: (bold emphasis added)

Lay means "to place something down flat," while lie means "to be in a flat position on a surface."

Most native speakers of any language have their common, vernacular errors. Native speakers often get this wrong, including myself. It is a bad habit to be anticipated and it is perfectly fine to correct us when we do, though some on the IPS may say correcting others' speech is not always most tactful. :-)
Nonetheless, this is a common mistake among native speakers, which indeed makes the language more difficult to learn for second-language learners.
Why do we make this mistake?
Most likely, we make this mistake because "lie" is the same word as to be dishonest...
lie 2 (Merriam-Webster):

to make an untrue statement with intent to deceive

...But that is just a guess. Mistakes happen in every culture and the habits of a culture tend to be contagious within that culture. Don't pick up our bad habit yourself.


text:
Q: Use angular-input-mask twice time followed In this code:

        CEP Origem:
        <input type="text" id="origem" ng-model="cep" ui-br-cep-mask>

        CEP Destino:
        <input type="text" id="destino" ng-model="cep" ui-br-cep-mask>

When I completed any one of the two the other have the same value, how can I change this?

A: Because both have the same model, provide different model for each input will solve this issue. You can also use  object and bind the keys.

    CEP Origem:
    <input type="text" id="origem" ng-model="cep.origem" ui-br-cep-mask>

    CEP Destino:
    <input type="text" id="destino" ng-model="cep.destino" ui-br-cep-mask>

A: This is simply because both of your inputs are using the same ng-model. Simply set a different one should help you

A: ng-model defines the variable that will be edited by your input.
So, if your inputs have the same ng-model, it will edit the same variable.

Here you just have to change the ng-model of your second input:
<input type="text" id="origem" ng-model="cep1" ui-br-cep-mask>
<input type="text" id="destino" ng-model="cep2" ui-br-cep-mask>


text:
Q: Android - multiple webViews with multiple webViewClient : shouldOverrideUrlLoading not called on new webViewClient I have an android activity with a fragment dedicated for multiple webviews.
I've implemented what i could about multiple webview methods including
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
    // source code here ...
}

For the first webview, shouldOverrideUrlLoading(..) gets called OK.
But as I follow some links and create a new webview,
setup excatly the same as the first one,
assign new webViewClient and new webChromeClient.
The new webViewClient override functions such as onPageStart(..), onPageFinished(..) will call ok,
but only shouldOverrideUrlLoading() does not get called on the new webview despite it has a totally new webViewClient instance.
I've checked the instance ids of both webViewClient and confirmed that they have different instance ids for each webviews (which is good because it means both webviews have actually different instances of webViewClients)
I have no clue why the new instance of webViewClient will not trigger shouldOverrideUrlLoading() function.
Can anybody help me? :(
Thanks!

A: Had a similiar situation.
In your web-client, you can implement the following:
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
       WebResourceResponse response = super.shouldInterceptRequest(view, request);
    return response;
}

and you can set a breakpoint in the middle to see what's going on.
My problem was that the request method was POST, and that did not trigger the shouldOverrideUrlLoading, so make sure that your request method is GET.


text:
Q: Eslint multiple configuration comments All,
I'm using this configuration comment at the top of my test files.
/* eslint-env mocha */

I would like to also include this comment.
/* eslint-disable no-console */

But I can't seem to get both of them to work together. I've tried the following.
// A
/* eslint-env mocha, eslint-disable no-console */

// B
/*
  eslint-env mocha
  eslint-disable no-console
*/

// C
/* eslint env: mocha, disable: no-console */

A: It will work like this.
/* eslint no-console: off */
/* eslint-env mocha */


text:
Q: Detecting a change in UISwitch This sounds trivial but I'm noticing some weirdness. I've wired up a handler for the Value Changed event of a UISwitch. What I would expect is that each time the handler is called the value of the switch would change. But that's actually not always the case. If you press the switch rapidly on/off the handler can get called consecutively with the SAME state for the switch (in my specific application this is an issue). So I'm wondering if anyone else has noticed this behavior and has figured out a good solution.

A: In iOS 11 a new UISwitch bug was introduced so I don't recommend subscribing to value changed events. Otherwise your callback will be triggered every time UISwitch's isOn attribute changes programmatically.
Instead:

*

*Subscribe for touch up inside event:

let switch = UISwitch()
switch.addTarget(self, action: #selector(onSwitchValueChanged), for: .valueChanged)

*Implement the callback method:

func onSwitchValueChanged(_ switch: UISwitch) {

}

*And now when you programmatically change isOn value, it won't trigger onSwitchValueChanged method.

switch.isOn = !switch.isOn // 'onSwitchValueChanged' is not triggered

A: Get state of switch in handler:
- (void)valueChanged:(UISwitch *)theSwitch {
   BOOL flag = theSwitch.on;
}

A: Each press you make doesn't immediately toggle the switch on/off. If the switch is in the off position, you can get a couple of presses in before it animates to the on position. Each of these presses are interpreted as "turn the switch on", since it is not considered "on" until the animation has completed. You get a "valueChanged" callback for each press despite the fact that the value hasn't actually changed yet.

A:    -(void) createSwitch
    {
        self.searchExistSearchNewSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0,0,0,0)];
        [self.searchExistSearchNewSwitch addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:self.searchExistSearchNewSwitch];
    }
    - (void)switchValueChanged:(UISwitch *)theSwitch
    {
        BOOL flag = theSwitch.isOn;
    }

A: Here's a solution that works for me.
It also sends a property "will/did change" notification when the switch is changed.
The event also functions correctly in that the before and after values are maintained correctly.
@interface MySwitch : UISwitch

@end

@implementation MySwitch
{
    BOOL _previousValue;
    BOOL _returnPreviousValue;
}

- (instancetype) initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder: aDecoder];
    if (!self) return nil;

    _previousValue = self.isOn;
    [self addTarget: self action: @selector(_didChange)
                forControlEvents: UIControlEventValueChanged];

    return self;
}

- (instancetype) initWithFrame: (CGRect) frame
{
    self = [super initWithFrame: frame];
    if (!self) return nil;

    [self addTarget: self action: @selector(_didChange)
                forControlEvents: UIControlEventValueChanged];

    return self;
}

- (BOOL) isOn
{
    return (_returnPreviousValue)
                        ? _previousValue
                        : [super isOn];
}

- (void) setOn:(BOOL) on animated: (BOOL) animated
{
    [super setOn: on animated: animated];

    _previousValue = on;
}

- (void) _didChange
{
    BOOL isOn = self.isOn;

    if (isOn == _previousValue) return;

    _returnPreviousValue = true;
    [self willChangeValueForKey: @"on"];
    _returnPreviousValue = false;

    _previousValue = isOn;
    [self didChangeValueForKey:  @"on"];
}

@end

A: Log the last state so you can tell if its changed state or has been triggered with the same state.

A: When you toggle the switch off/On the "value changed" has been called.So you can detecting a change in switch by calling method on valueChanged.

A: My problem was a stupid one... I was expecting the enabled value to change, but obviously that isn't the correct value to inspect upon the toggle of the switch, the on or isOn is the correct thing to use.


text:
Q: SQL MS Access just show 2 Data with same ID my problem is just to show two rows of Data with same ID.
My Table looks like this:
------------------------------
- FlatDestID - Trefferspalte -
- 444555666  -       K       -
- 444555666  -       1       -
- 444555666  -       1       -
- 111222333  -       K       -
- 111222333  -       1       -
- 111222333  -       1       -
------------------------------

And i want to have my Table like this
------------------------------
- FlatDestID - Trefferspalte -
- 444555666  -       K       -
- 444555666  -       1       -
- 111222333  -       K       -
- 111222333  -       1       -
------------------------------

Sometimes i have the same ID four to five times. And i just want to show the first two Data for each FlatDestId like in the second example. That means if you have 5 times the same FlatDestId then just show the FlatDestId with "Trefferspalte = K" and then a secon Data with the same FlatDestId and "Trefferspalte = 1"
I hope you can understand my Question and the problem i need Solution for.
Greatings from Germany
---------- EDIT ----------
I have for "Trefferspalte" the Values K and 1-6 and i want to see always K and then another FlatDestId with 1 or 2 or 3 or 4 or 5 or 6!
The Solution DISTINCT show's FlatDestId and Trefferspalte with all the Values that Exist for the FlatDestId and not K and just any Trefferspalte. I need to have two Values.

A: Access doesnt like much nested SQL queries, so first create a Query with this SQL :
SELECT K.FlatDestID, T.AnyTrefferspalte
FROM
(
    SELECT DISTINCT FlatDestID
    FROM <yourTable>
    WHERE Trefferspalte = 'K'
) K
INNER JOIN
(
    SELECT FlatDestID, MIN(Trefferspalte) AS AnyTrefferspalte
    FROM <yourTable>
    WHERE Trefferspalte <> 'K'
    GROUP BY FlatDestID
) T
ON K.FlatDestID = T.FlatDestID

The goal is to know which are the FlatDestID that have both a 'K' Trefferspalte row and any other row. If there are multiple non-K Trefferspalte, here with MIN(Trefferspalte), I have chosen to keep their minimum value. You can change it to MAX() to keep the higher value, or to FIRST() to keep the first one encountered, which in fact means random.
Name your query like you want, I have chosen TempQuery
Then, this query should give you the expected results:
SELECT FlatDestID, 'K' AS Trefferspalte FROM TempQuery
UNION ALL
SELECT FlatDestID, AnyTrefferspalte AS Trefferspalte FROM TempQuery
ORDER BY FlatDestID

On a side note: your table structure is weird and needs a serious redesign that would avoid you a lot of headaches. A Primary Key would be a good start.

A: Make use of DISTINCT to remove duplicates, this will show your 2 rows. When you have more than 2 different values for Trefferspalte you will have to use some other method.
SELECT DISTINCT FlastDestID, Trefferspalte
FROM <yourTable>

A: You may want to make both columns your primary keys so that it'll thrown an error if you receive duplicate values (so you won't save it in the table). If that's the existing setup and you can't do anything about it, try DISTINCT. If it won't work, then try grouping it (you just need to add a new column in your query:
SELECT FlatDestID, Trefferspalte, COUNT(*) FROM YourTable GROUP BY FlatDestID, Trefferspalte


text:
Q: Magento 1 - Fresh 1.9.4.5 style not loading I just installed a fresh Magento 1.9.4.5, but the style is not loading. This is the web setup wizard:

I am using PHP 5.6

A: I figured it out, it was a right problem:
Solution. Go to your webroot and execute these two commands:
find . -type d -exec chmod 775 {} \;
find . -type f -exec chmod 664 {} \;


text:
Q: Sum of the four 32bits elements of a _m128 vector I'm using intrinsics to optimize a program of mine. But now I would like to sum the four elements that are in a __m128 vector in order to compare the result to a floating point value. For instance, let's say I have this 128 bits vector : {a, b c, d}. How can I compare a+b+c+d to e, where e is of type float ?
Does SSE2 or SSE3 provide a way to do that simply or do you have any code snippet that could help me ? Thanks !

A: The best I can up with is this:
; assumes    xmm0 = [0, B, 0, A] or similar
mulps xmm0,xmm0   ; [0, B*B, 0, A*A]
xorps xmm1,xmm1
movhlps xmm1,xmm0 ; [0, 0, 0, B * B]
addps xmm0,xmm1   ; [0, 0, 0, A * A + B * B]

If A and B absolutely have to be in the low quadword then as far as I can tell you need a shuffle, which is slower on pre-Penryn (and on a Penryn the DPPS solution is available).


text:
Q: Add UIBarButtonItem action in Swift programmatically I'm trying to connect an action to my UIBarButtonItem in Swift, programmatically, without any Storyboard.
I can't do it this way :
var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action: "sayHello")

Since I use an external library (Font_Awesome_Swift) which doesn't have a constructor to create an UIBarButtonItem with an icon from the library. So I'm doing it this way :
let rightButtonItem = UIBarButtonItem()
rightButtonItem.FAIcon = FAType.FACamera

Then, I want to be able to attach an action to this UIBarButtonItem. I have found in another answer, this solution :
UIApplication.sharedApplication().sendAction(barButtonItem.action, to: barButtonItem.target, from: self, forEvent: nil)

But I don't really understand how to use it. Where should I indicate the name of the selector ?
Thanks!

A: Swift makes adding an action to a UIBarButtonItem easy for us.
let rightBarButton = UIBarButtonItem()
// add an action
rightBarButton.action = #selector(yourAction)

A: Ok, just after posting this question, I have found an easy way to solve my issue... With the "default" UIBarButtonItem constructor and the following code :
let rightButtonItem = UIBarButtonItem(title: "Camera", style: .Plain, target: self, action: "launchCamera")
rightButtonItem.FAIcon = FAType.Camera

A: for example i write this code for UIBarButtonItem:
 navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action , target: self, action: #selector(shareTapped))

and selector code is :
func shareTapped() {

//         for share in Social media or Save in local
//        let vc = UIActivityViewController(activityItems: [imageView.image!], applicationActivities: [])
//        vc.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
//        present(vc, animated: true)

        // this line its for share photo in facebook or twitter
        if let vc = SLComposeViewController(forServiceType:  SLServiceTypeTwitter) {
            vc.setInitialText("Look at this great picture!")
            vc.add(imageView.image!)
            vc.add(URL(string: "http://www.photolib.noaa.gov/nssl"))
            present(vc, animated: true)
        }
    }

and i use image in my app and because of this i using image view.image


text:
Q: How can I install metatracker from source? Following a question I raised a few weeks back, I would like to install tracker and see how it works with natty. The latest stable release of metatracker is 0.10.10, but unfortunately, only version 0.8.17 can be found packaged.
Does anyone know how can I install tracker from source, and if anybody has already tried it, please let me know how well does it work with natty.
Thanks.

A: You can install Tracker 0.9.26 from their PPA. There is also a stable PPA, but there's nothing for 11.04 there yet.


text:
Q: Show Vertical Graph Bar Percentage in the middle of div I have a progress bar that I need to be able to show the percentage text always in the middle of the progress bar. Currently, only the values are not vertically centered inside the progress bar. I need to do this only with html and CSS and not jQuery or javascript

.vertical .progress-bar {
  float: left;
  height: 100px;
  width: 40px;
  margin-right: 10px;
}
.vertical .progress-track {
  position: relative;
  width: 40px;
  height: 100%;
  background: #fff;
  border: 1px solid #ebebeb;
}
.vertical .progress-fill {
  position: relative;
  height: 50%;
  width: 40px;
  color: #fff;
  text-align: center;
}

      100%

      80%

      60%

        0%

A: Revised answer below; see Fiddle here: https://jsfiddle.net/ybygucn7/
HTML:

             100%

CSS:
.vertical .progress-bar {
  height: 100px;
  width: 40px;
  display: inline-block;
  margin: 0 5px;
  font-size: 12px;
  text-align: center;
}

.progress-bar .progress-track {
  width: 100%;
  height: 100%;
  background: #fff;
  border: 1px solid #ebebeb;
  position: relative;
}

.vertical .progress-fill {
    width: 100%;
    color: #fff;
    text-align: center;
    position: absolute;
    z-index: 0;
    bottom: 0;
}

.vertical span {
    position: absolute;
    z-index: 1;
    top: 50%;
    width: inherit;
    left: 0;
    transform: translateY(-50%);
}

A: I have made changes in your HTML and in CSS .progress-bar overflow has hidden, try this.

.vertical .progress-bar {
  float: left;
  height: 100px;
  width: 40px;
  margin-right: 10px;
  overflow:hidden;
}
.vertical .progress-track {
  position: relative;
  width: 40px;
  height: 100%;
  background: #fff;
  border: 1px solid #ebebeb;
  //overflow:hidden;
}
.vertical .progress-fill {
  position: relative;
  height: 50%;
  width: 40px;
  color: #fff;
  text-align: center;
}

      100%

      80%

      60%

        0%


text:
Q: IPv6 - country detection I have a CSV file downloaded from Maxmind which contains IPv6 data. I need to upload it to MySql table and then use this table to detect a country by IPv6.
So the first question is what the MySql type should be LONGSTART and LONGEND fields in my MySQL table as max INTEGER length can be of 20 while I have 42540488558116655331872044393019998208 number?
And the other question is how to build a MySql query in order to find an IP address between LONGSTART and LONGEND? I use a function( ipv6_numeric($ip) ) which converts '2001::11ff:ffff:f' IPv6 address into a long number like 2540488558116655331872044393019998208.
Thanks for advance!

A: You can use the following simple SQL query.
SELECT * FROM `geoip2`
WHERE [SEARCH IP NO] <= LONGEND LIMIT 1


text:
Q: Yii CGridView horizontal scroll I develop yii application and have CGridView with many columns. I want to scroll the CGridView horizontal but can't find how.

A: You can put grid into container with fixed width and overflow: auto;.
<div class="CGridViewContainer">
    <!-- CGridView here -->
</div>

And CSS:
.CGridViewContainer { width: 960px; overflow: auto; }

But I believe that spanning of the columns will be better way of presenting the table. Don't know how to make headers or is it possible w/o modifications.

A: If you set overflow: scroll-x on the CSS for your grid, that should setup horizontal scrolling in your browser


text:
Q: htaccess rules not working everytime, sometimes 404 Okay so this is a bit odd, my htaccess rules don't seem to work every time. Sometime it sends people to a 404 page. But if they try the same link again, it then works.
Here my my rules:
  RewriteRule ^articles/(.+?)\.([0-9]+)/?$ /index.php?module=articles_full&aid=$2&title=$1 [N,NC,QSA]

  RewriteRule ^articles/(.+?)\.([0-9]+)/page\=([0-9]+)?$ /index.php?module=articles_full&aid=$2&title=$1&page=$3 [N,NC,QSA]

Can anyone see anything wrong with those rules? It basically turns index.php?module=articles_full&aid=123&title=title to /articles/title.123
I also have this to redirect old links to the new ones, don't know if anyone knows if they somehow conflict sometimes?
  RewriteCond %{QUERY_STRING} threads/(.*)\.([0-9]+)/*

  RewriteRule index.php /articles/%1\.%2?from=oldSite [R=301,L]

A link to my full htaccess: http://pastebin.com/G0AxxiHb
Looking through error logs for today (30th) these jump out at me:
[Wed Jan 30 09:44:30 2013] [error] [client 2.229.9.52] File does not exist: /home/gamingon/public_html/articles, referer: http://plus.url.google.com/url?sa=z&n=1359539066078&url=http%3A%2F%2Fwww.gamingonlinux.com%2Farticles%2Frolling-survival-a-new-alpha-funded-game-on-desura.1681&usg=V4xV32LxoWJ1cPOvrD_XZgftgN8.

That one looks like a link i posted on G+, i'm guessing because it has added "&usg=V4xV32LxoWJ1cPOvrD_XZgftgN8" to the end of the url?
[Wed Jan 30 11:34:43 2013] [error] [client 100.43.83.149] File does not exist: /home/gamingon/public_html/$10,000 to finish on Kickstarter

That seems to miss "/articles/", the id and it has spaces in the name? Not sure how that happened maybe someone manually typed it?
Seems to be a few of these too:
[Wed Jan 30 06:32:38 2013] [error] [client 94.246.88.189] File does not exist: /home/gamingon/public_html/articles

Do you think maybe i need to have something added to the two /articles/ rules to check for links that get stuff added onto the end? Like links from twitter, g+ etc?


text:
Q: Can you use Javascript popups in js2py I want to create a function in python that will create a javascript confirm() popup window when called, and return the user input.  I need this as a tool for the website I'm creating (I'm using Django so most of my 'back end' code is in python).
So far I've discovered js2py as a possible solution, but I am not sure if this package works with the javascript popup functions like confirm() and alert().
So far I've tried these approaches:
import js2py

def Error_Popup(message):
  retval = js2py.eval_js('var retval = confirm(message); retval')
  return retval

and
import js2py

def Error_Popup(message):
  retval = js2py.eval_js('function continue(message){var retval=confirm(message); return retval}')
  return retval

But I keep getting the error: PyJsException: ReferenceError: confirm is not defined when I run the functions.
Is possible to use js2py with javascript popups and if so what the correct syntax for it is?
-- EDIT --
Is it at all possible to create a javascript-like popup from python?  I've tried things like easygui but they are slow.  I would really like to have something that I can put in a python function so it interacts well with my Django website.


text:
Q: find equivalent partitions of an array Suppose to have an algorithm that find a partition of an array nodes=[1:10] based on some minimization problem. The output of the algorithm will be an array of indices indicating to which partition a certain nodes is assigned. For example: part=[1 1 1 1 3 3 2 2 2 2].
This algorithm has an issue though. It has a stochastic component and sometimes it can return the same partition but with a different numbering. For example part2=[2 2 2 2 3 3 1 1 1 1]. In this case part1 and part2 are de facto the same partition.
Let's say that I need to run the partitioning algorithm 5 times. The output will be a 5x10 matrix A. At the end I need to see how many different partitions the algorithm found. This implies that I need to know how many equivalent partitions are present in A.
I wrote an algorithm that does this but is really slow for large inputs.
Here an example of the input:
clusters=[ 1,1,2,2;
           1,1,2,2;
           2,2,1,1;
           1,2,1,2;
           2,1,2,1;
           3,1,2,1;
           2,1,2,1;
           3,1,2,1;
           1,2,1,2];

for which I obtain the different partitions, the most frequent partition and the number of times it occurs m:
true_clusters =

 1     1     2     2
 1     2     1     2
 3     1     2     1

frequest =

 1     2     1     2

m =

 4

Does anyone know a fast way to solve the problem?

A: I don't know if it's fast enough for you:
[~,~,c] = unique(clusters','rows','stable');

c_unique = unique(c,'rows')

A: This is a vectorized version:
Consider rows [1 2 1 2] and [3 1 2 1]  and [ 2 1 2 1] that have the same pattern because in all of them consecutive elements of each vector are different from each other so diff(clusters,1,2)~=0 for those rows generates the same pattern [1 1 1].
But that is not sufficient to get a correct answer for the algorithm.
Also for each row it is required to have unique elements that appear in it.
so in  [1 1 2 2] the unique elements are [1 2] and for [3 1 2 1] unique elements  are [1 2 3]
equally a logical vector can be created that represents if each of [1 2 3] are member of a row so for [1 1 2 2] logical vector is [1 1 0] and for [3 1 2 1] is [1 1 1] that accumarray do the mentioned task.
Concatenating two patterns as [diff(clusters,1,2)~=0 , ac] create an array that it's rows represent different partitions. then unique function can be applied to extract unique partitions
ac=accumarray([ repmat((1:size(clusters,1)).',size(clusters,2),1) clusters(:)],1,[],@any);
[~, v, I]=unique([diff(clusters,1,2)~=0 , ac],'rows');
many= hist(I,I(v));
true_clusters = clusters(v,:);
[m,im] = max(many);
frequest = true_clusters(im,:);

Result:
many = 3 4 2

true_clusters =

   2   2   1   1
   1   2   1   2
   3   1   2   1

m = 4

frequest = 1 2 1 2


text:
Q: Babel, Webpack and Mobx: TypeError: Cannot read property 'authenticate' of undefined In the process of integrating ESLint to a MobX with decorators React project, I run into the problem of the stores being undefined.
I have read a lot of the posts regarding how to use decorators with mobx and there's a definite, reported way to make it work, but at the same time there's a sentiment in the air to just not use them and instead use the wrapper functions the decorators replace. I would not like to lose the readability and ease of use in way of a solution, but at this moment I'm not sure what else I can try to have this working.
At this moment I have two separate git branches in my project and can provide examples of the working build with decorators, as mentioned above the problem arises when adding linting tools
Code samples in question below:
App.jsx
import React, { Component } from 'react';
import { Route, withRouter } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import LazyRoute from 'lazy-route';
import styles from './styles/app.css';

@withRouter
@inject('store')
@observer
export default class App extends Component {
  constructor(props) {
    super(props);
    this.store = this.props.store;
  }
  componentDidMount() {
    //here's where the error is triggered, authenticate is a function in the store but it throws undefined
    this.store.appState.authenticate();
  }
  render() {
    return (
      <div className={`container-fluid ${styles.wrapper}`}>
        <Route exact path="/" render={props => <LazyRoute {...props} component={import('./Home')} />} />
        <Route exact path="/profile" render={props => <LazyRoute {...props} component={import('./Profile')} />} />
        <Route exact path="/balance" render={props => <LazyRoute {...props} component={import('./Balance')} />} />
        <Route render={props => <LazyRoute {...props} component={import('./Home')} />} />
      </div>
    );
  }
}

.babelrc
{   "presets": ["react", "es2015", "stage-1"],   "plugins": ["transform-decorators-legacy"] }

dependencies:
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.18.0",
"babel-loader": "^6.2.7",
"babel-plugin-transform-async-to-generator": "^6.16.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-1": "^6.16.0",
"css-loader": "^0.25.0",
"extract-text-webpack-plugin": "^2.0.0-beta.4",
"html-webpack-plugin": "^2.22.0",
"image-webpack-loader": "^2.0.0",
"node-sass": "^3.10.1",
"postcss-loader": "^0.13.0",
"react-hot-loader": "next",
"resolve-url-loader": "^1.6.0",
"rimraf": "^2.5.4",
"sass-loader": "^4.0.2",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.5"
  },
  "dependencies": {
    "axios": "^0.15.0",
    "babel-eslint": "^8.0.0",
    "babel-preset-env": "^1.6.0",
    "bootstrap": "^3.3.7",
    "create-react-class": "^15.6.0",
    "eslint": "^3.19.0 || ^4.3.0",
    "eslint-config-airbnb": "^15.1.0",
    "eslint-config-prettier": "^2.5.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-import": "^2.7.0",
    "eslint-plugin-jsx-a11y": "^5.1.1",
    "eslint-plugin-prettier": "^2.3.0",
    "eslint-plugin-react": "^7.1.0",
    "faker": "^3.1.0",
    "http-server": "^0.10.0",
    "jquery": "^3.2.1",
    "lazy-route": "^1.0.7",
    "mobx": "^2.5.2",
    "mobx-react": "4.0.0",
    "mobx-react-devtools": "^4.2.6",
    "moment": "^2.18.1",
    "package": "^1.0.1",
    "react": "^15.6.1",
    "react-bootstrap": "latest",
    "react-bootstrap-date-picker": "^5.1.0",
    "react-dom": "^15.6.1",
    "react-loader": "^2.4.2",
    "react-router-dom": "latest",
    "react-stripe-elements": "^0.0.8",
    "rfx-core": "^1.5.3",
    "transform-runtime": "^0.0.0",
    "whatwg-fetch": "^1.0.0"
}

webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: ['webpack-dev-server/client?http://0.0.0.0:3000', 'babel-polyfill', 'whatwg-fetch', './src/index.jsx'],
  devServer: {
    contentBase: path.resolve(__dirname, 'dist'),
    port: 8000,
    host: 'localhost',
    publicPath: '/',
    historyApiFallback: true,
    disableHostCheck: true,
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json'],
  },
  output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: 'app.[hash].js',
  },
  devtool: 'eval',
  module: {
    rules: [
      {
        test: /\.js$|jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss|css$/,
        use: [
          'style-loader',
          'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
          'postcss-loader',
          'resolve-url-loader',
          'sass-loader?sourceMap',
        ],
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        use: [
          'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
          {
            loader: 'image-webpack-loader',
            options: {
              progressive: true,
              optimizationLevel: 7,
              interlaced: false,
              pngquant: {
                quality: '65-90',
                speed: 4,
              },
            },
          },
        ],
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: 'url-loader?limit=10000&mimetype=application/font-woff',
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: 'file-loader',
      },
      {
        enforce: 'pre',
        test: /\.jsx?$/,
        loader: 'eslint-loader',
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({ hash: false, template: './index.hbs' }),
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /nb/),
  ],
};

Full console error message:
Uncaught TypeError: Cannot read property 'authenticate' of undefined
at App.componentDidMount (webpack:///./src/components/App.jsx?:54:26)
at App.target.(anonymous function) (webpack:///./~/mobx-react/index.js?:262:13)
at eval (webpack:///./~/react-dom/lib/ReactCompositeComponent.js?:264:25)
at measureLifeCyclePerf (webpack:///./~/react-dom/lib/ReactCompositeComponent.js?:75:12)
at eval (webpack:///./~/react-dom/lib/ReactCompositeComponent.js?:263:11)
at CallbackQueue.notifyAll (webpack:///./~/react-dom/lib/CallbackQueue.js?:76:22)
at ReactReconcileTransaction.close (webpack:///./~/react-dom/lib/ReactReconcileTransaction.js?:80:26)
at ReactReconcileTransaction.closeAll (webpack:///./~/react-dom/lib/Transaction.js?:209:25)
at ReactReconcileTransaction.perform (webpack:///./~/react-dom/lib/Transaction.js?:156:16)
at batchedMountComponentIntoNode (webpack:///./~/react-dom/lib/ReactMount.js?:126:15)

A: I faced with that problem. That may help you:
1) Create a file in a root of project jsconfig.json containing following:
{
  "compilerOptions": {
      "experimentalDecorators": true
  }
}

2) You've already install "babel-plugin-transform-class-properties", but maybe didn't use it. Try add 'transform-class-properties' to .babelrc in plugins section right after 'transform-decorators-legacy', in my case it helped me. Your plugins in .babelrc should looks like:
plugins: [
       'transform-decorators-legacy',
       'transform-class-properties',
 ]


text:
Q: TeXnicCenter: names of files in red instead of black, why? In the files window the names of the files are most often in red and in some rare cases in black; would someone know why?

A: Only if you had build an project TeXnicCenter shows you the the involved files.
Files that can be found by TeXnicCenter are printed in black, files in red can not be found by TeXnicCenter. But the red color of the filename does not mean, that the file can not be seen by the system.
For example in my project the bib file is printed in red, because I placed it in an special directory to be able to use this bib file with several projects. MiKTeX has no problems to find and use this bib file but TeXnicCenter does not know the path to that file.
Summarise: the red color of an filename shows you that there could be an problem with that file, but it could also be that TeXnicCenter is simply not able to see the path to it ...


text:
Q: EXCEL VBA CSV Date formatting issue I am an Excel VBA newbie. My apologies if I am asking what seems to be an obvious question.
I have a CSV text file I am opening in an Excel worksheet. One row of the file contains date information formatted as "YY-MMM', (ie: 9-FEB, or 10-MAY). When the Excel spreadsheet opens the file the date information is changed to "mm/dd/yyyy" format and reads as 02/09/2009 or 05/10/2009 where the YY-MMM is now MM/YY/2009, (ie: the 9-FEB becomes 02/09/2009, and the 10-MAY becomes 05/10/2009).
I would like to know if it is possible to reformat the field from YY-MMM to mm/01/yyyy.
I have tried to parse the date field after converting it to text with
Range("B11", "IV11").NumberFormat = "text"

However, then the value is a serial date and non-parsable.
I have been unsuccessfully looking for a list of the NumberFormat options.
If you can point me in a direction it will be much appreciated.

A: Just to answer a part of your question, here is the list of date formatting options (excluding time):
d = day of month, e.g. 7
dd = zero-padded day of month, e.g. 07
ddd = abbreviated day name, e.g. Thu
dddd = full day name, e.g. Thursday

pretty much the same for month...
m = month number, e.g. 7
mm = zero padded month number, e.g. 07
mmm = abbreviated month name, e.g. Jul
mmmm = full month name, e.g. July

years are simpler...
yy = 2 digit year number, e.g. 09
yyyy = 4 digit year number, e.g. 2009

you can combine them and put whatever separators you like in them
e.g.
YY-MMM, 09-FEB
DDDD-DD-MMM-YY, Wednesday-04-Feb-09
dd/mm/yyyy, 04/02/2009
mm/dd/yyyy, 02/04/2009

I've just been trying a few things out and I think your best bet is to change the format in the text file to conform to a more standard date arrangement.  If you can reverse them (e.g. MMM-YY) you'll be fine, or split them into separate columns (what if when you import you define - as a separator as well as comma?).  This is one case where Excel trying to be clever is a pain.
HTH

A: If you are currently using File > Open to open the CSV file then try Data > Import External Data > Import Data instead. This brings up the text import wizard which might give you more flexibility in how to import the file. Specifically, it lets you declare a column in the file as being text so that Excel does not try to parse the value
As Simon has explained, your terminology for the current date format is not correct. 9-FEB corresponds to d-mmm format and 02-19-2009 (NB deliberately changed to an unambiguous date for this example; 02-09-2009 is 9th Feb in the US but 2nd Sept in the UK) corresponds to mm-dd-yyyy
If you wanted to change the NumberFormat to text for the range starting in cell B11 and ending in cell IV11 then you would use:
Range("B11:IV11").NumberFormat = "@"
@ signifies text format and you need the : operator to indicate a contiguous range of cells. Your original example of Range("B11","IV11") actually indicates the union of cells B11 and IV11 and thus would only have affected two cells
It is unusual to have your data structured in rows rather than columns. Rather than having your dates in row 11, it would be more common to have them in column K instead so that you would use Range("K2:K65535") or just Rows("K") Most of the built-in Excel stuff like Sort and AutoFilter assume that your data is laid out in columns anyway. Row 1 traditionally contains the column names and then each subsequent row contains an individual record. You might want to look at how your CSV file is being generated to see if you can switich it to a more usable column-based structure
If you have a date like 19-FEB as text in a cell then, assuming that you always want the year part to be the current year, you can change it to the first day of the month in mm/dd/yyyy format in VBA. This example only changes one cell but you can use it as the basis for a wider solution:
Option Explicit

Sub main()

Dim strOrigValue As String

With ThisWorkbook.Worksheets("Sheet1").Range("B11")
    strOrigValue = .Value

    .NumberFormat = "mm/dd/yyyy"
    .Value = DateSerial(Year(Date), Month(strOrigValue), 1)
End With

End Sub

DateSerial creates a date serial number from the given year, month and day. Year(Date) extracts the year part from the current system date, Month(strOrigValue) takes the month part from the data that's already in the cell and we want the first day of the month

A: In order to read in a date, you can do something like this:
myDate = DateValue(dateText)

although there are caveats to how excel may interpret dates, and what technical limits it has in what dates it may store.  (you may need to read up on maximum and minimum dates, and how excel interprets two-digit years >30 vs <30, among other things)
In order to format the date, you can use one of three functions:
myDateText = DatePart("yyyy", myDate) & "/" & DatePart("mm", myDate) & "/" & DatePart("dd", myDate)

or this
Format (myDate, "yyyy/mm/dd")

or this
FormatDateTime(#1/1/2020#, vbShortDate)

You can search google for more documentation on each function.  For the format function, you will want to find a good reference -- I've seen some rather incomplete ones.   MSDN tends to have good ones, but not always.  Feel free to bump this answer if you want more details.

A: This assumes your 2 digit year is 2000. Once you end up with your incorrect date 9-Feb = 02/02/2009, you can convert this to the date you want with the formula:  =DATE(Day(B11)+2000,Month(B11),1)


text:
Q: A hands-on description of a "completion" of the free commutative monoid on countably many generators This is basically an I'm-weak-at-algebraic-geometry question.  I asked it as a warm-up question here, but Ilya N asked me to break that post up into several questions.
Consider the free commutative monoid $X$ on countably many generators.  Let $A$ be the algebra of all functions $X \to \mathbb C$.  Then $A$ is a commutative and cocommutative bialgebra, and hence a commutative monoid object in $(\text{CAlg})^{\rm op}$, where $\text{CAlg}$ is the category of commutative algebras.  A global point of $A \in (\text{CAlg})^{\rm op}$ is an algebra homomorphism $A \to \mathbb C$.  The set of global points of $A$ is naturally a commutative monoid that contains $X$ as a submonoid.
What are all the global points of $A$?  I'm pretty sure that there are more than just the points of $X$.  The form a monoid, because $A$ is a bialgebra: is there a reasonable description of the monoid structure?

A: Preliminaries
First part of your question doesn't use the bialgebra structure. That is, you have a space of functions on countable many points which I'll denote $A = \mathbb C_1\times \mathbb C_2\times\cdots \times\mathbb C_n\times\cdots$ equipped with $+$ and $\times$ pointwise. You would like to classify all algebra maps $\varphi: A\to \mathbb C$.
To start, note that idempotents must go to idempotents, of which $\mathbb C$ has only two: $0$ and $1$. Moreover, $1\times1\times\cdots \mapsto 1$ (unless the whole map is trivial).
Classification of points
Consider characteristic functions $\lambda_n$ which take value from point labeled $n$. As $\lambda_n^2 = \lambda_n$, we must have $\varphi(\lambda_n) = 0$  or $1$. There are three cases:

*

*there are two indices $i, j$ such that $\varphi(\lambda_i) = \varphi(\lambda_j) = 1$. This is impossible: $0 = \varphi(\lambda_i\lambda_j) = 1$.

*there exists exactly one index $i$ for which $\varphi(\lambda_i) = 1$. This implies $\varphi(f) = \varphi((1-\lambda_i)f + \lambda_if)  = f(i)$.

*all functions $\lambda_i$, and, therefore, all finite sums from $A$, lie in the kernel of $\varphi$.

The maps of the latter type are indeed the "extra" points. Note, however, that they are "wild" and can be easily killed by some extra finitness assumptions, for example the following "limit of zeroes" property: if $\varphi$ restricted to all finite subsets is 0, then $\varphi$ is 0.
Wild maps
You can construct examples of these wild maps using the axiom of choice. To do that, make the elements of the form $a\times a \times \cdots$ and all their finite modifications to map to $a$; denote those elements $A_0$. Next, select an arbitrary $T_1\in A$ which is transcendental over $A_0$ and map it to arbitrary $t_1\in \mathbb C$. This will fix all elements that lie in algebraic closure $A_1 = A_0(T_1)$. Do that again for $T_2$ and repeat until you have nothing left. At each step you're producing a correct map $A_n \to \mathbb C$, so you get the final map $A\to \mathbb C$ as the limit of those.
Conversely, any wild map can be constructed by the above process, assuming all necessary set-theoretic things. So, the answer is, the wild points are classified by maps from this terribly non-constructive sequence of $T_i$ (of cardinality the same as $A$, that is, continuum) to $\mathbb C$. Those are again in cardinality of continuum.
Monoid structure
One now is reminded that $A$ came with a natural basis enumerated by numbers $(n_1, n_2, \dots, n_k, \dots) \in \mathbb Z^+\oplus\mathbb Z^+\oplus\cdots\oplus\mathbb Z^+\oplus\cdots$ (which is isomorphic to   $\mathbb Z_{>0}^\times$). Therefore, it should be possible to add any two points (denoted $\oplus$). The following properties are clear:

*

*regular points add normally as $n_k = n_k' + n_k''$;

*adding wild point to either regular or wild point results in a wild point.

Now, although you could write explicitly some wild points, nearly all of them  are too hard to describe. The best approximation to the resulting picture is probably this: imagine a set of wild points $W$; the whole space is $W \times  \mathbb Z^+\times \mathbb Z^+\times\cdots$. The remaining question, therefore, is what monoid $W$ is equivalent to. For that, you need to settle these questions:

*

*is it true that you cannot have $w_1 \oplus w_2 \oplus \cdots\oplus w_n = r$ where $r$ is a regular point;

*whether you can subtract them;

*whether and how wild points are divisible by naturals.

Operations on wild points
I think now is certainly time to post another question :)

A: When the field is $k=\mathbb F_2$ instead of $\mathbb C$, you can construct algebra morphisms from the $k$-algebra of functions on an infinite set to $k$ which are not evaluations, by using an ultrafilter.
Let $U$ be a non-principal ultrafilter on $X=\mathbb N$, and let $I$ be the ideal of $k(X)$, the algebra of $k$-valued functions on $X$, such that a function $f:X\to k$ is in $I$ iff $\{x\in X:f(x)=0\}\in U$. This is indeed a proper ideal, as one checks at once, and it is in fact maximal. Moreover, $k(X)/I$ has exactly two elements, so from $U$ we get a morphism $\epsilon:k(X)\to k$. As the ultrafilter $U$ is not principal, this map $\epsilon$ is not an evaluation.
(If you do the same with $\mathbb C$, one cannot prove that $k(X)/I$ is again $\mathbb C$; indeed, it is generaly not!) (On the other hand, the same is true for any finite field, I guess, because saying that the field has $q$ elements is a first order property of the field and Łoś's theorem applies... maybe someone with a firmer grasp on this can confirm this?)


text:
Q: Inject Spring bean within RESTEasy Resource at Test time Within a Unit/Integration Test, I'm trying to use the RESTEasy embedded server TJWSEmbeddedJaxrsServer or POJOResourceFactory inorder to simulate through a MockHttpRequest.get("/data") a resource call for test purpose.
My problem is that based on the use of the server or the Resource factory I'm not able to have a non null instance of spring beans which are injected normally within my resources.
Here's some code for clarification, thanks in advance.
Spring application context :
<context:annotation-config />
<context:component-scan base-package="com.cdcfast.service" />
<bean id="simpleResource" class="com.cdcfast.rest.SimpleResource" />

SimpleResource.java :
@Component
@Path("/data")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class SimpleResource {

@Autowired
private SimpleService service;

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Data> getData() {
    return MockDataBase.getInstance().getRows();
}

Unit Test :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:/test/spring/testApplicationContext.xml" })
public class FakeTest {

private Dispatcher dispatcher;

@Before
public void before() {
    dispatcher = MockDispatcherFactory.createDispatcher();
    POJOResourceFactory noDefaults = new POJOResourceFactory(SimpleResource.class);
    dispatcher.getRegistry().addResourceFactory(noDefaults);
}

@Test
public void aTestThatAlwaysPass() throws URISyntaxException {
    MockHttpRequest request = MockHttpRequest.get("/data");
    MockHttpResponse response = new MockHttpResponse();
    dispatcher.invoke(request, response);
    Assertions.assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
    Assertions.assertThat(response.getContentAsString()).isNotNull().isNotEmpty();
}

}

A: I've had this before because the RESTEasy factories create the POJO rather than Spring so they don't get wired up which can be worked around in the full container but is less easy in a test. The best way around this is to get a handle to your POJO once the factory creates it and then do something similar to this:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(myPojo);

I personally ended up having Spring create the RESTEasy beans using the RESTEasy-Spring plugin and then launching my tests using Jetty, not sure if that is an option for you though.

A: I exeprienced same problem and i'have solved in similar way as James did:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-context-test.xml" })
public class TestMyService {

    Dispatcher dispatcher;
    private String username = "user";

    @Autowired
    ApplicationContext context;

    @Before
    public void setUp() {

    MyService g = new MyService(); //rest service with @autowired spring beans
    context.getAutowireCapableBeanFactory().autowireBean(g);
    dispatcher = MockDispatcherFactory.createDispatcher();
    dispatcher.getRegistry().addSingletonResource(g);
    }

    @Test
    public void TestRest() {
    MockHttpRequest request;
    try {
        request = MockHttpRequest.get("/rest/service").header("LOGON_USER", username);
        MockHttpResponse response = new MockHttpResponse();

        dispatcher.invoke(request, response);
        assertTrue("Error, unexpected status code: " + response.getStatus(), response.getStatus() == 200);
        LoggerFactory.getLogger(this.getClass()).info("********** " + response.getContentAsString());
    } catch (URISyntaxException e) {
        Log.error(e.getMessage(), e);
        fail(e.getMessage());
    }
    }

}


text:
Q: Insert data between 30 minute time intervals I want to divided my to my time interval depending to the start time and end time. To explain it further, let me have this example.
I have this table:
User           Elapsed Time        Start Time            End Time
User01         01:05               07-02-2015 08:45      07-02-2015 09:50

I want to divide its elapsed time to 30 minute time interval so that i will have an output like this.
Interval From        Interval To         User       Elapsed Time
07-02-2015 08:30     07-02-2015 09:00    User01     00:15
07-02-2015 09:00     07-02-2015 09:30    User01     00:30
07-02-2015 09:30     07-02-2015 10:00    User01     00:20

Thanks in advance

A: Here's a different approach that doesn't rely on loops or additional tables, however it does touch the source table twice. (You'll have to replace dbo.aTable with the name of your actual table, and add where clauses where commented below if you want to filter.)
DECLARE @i INT = 30; -- interval in minutes

DECLARE @ft SMALLDATETIME, @lt SMALLDATETIME;
SELECT @ft = MIN([Start Time]), @lt = MAX([End Time]) FROM dbo.aTable -- WHERE?;

;WITH d1(dt) AS
(
  SELECT TOP (DATEDIFF(MINUTE,@ft,@lt)/@i+2)
    DATEADD(MINUTE,DATEDIFF(MINUTE,0,DATEADD(MINUTE,@i*(ROW_NUMBER()
    OVER (ORDER BY [object_id])-1),@ft))/@i*@i,0)
  FROM sys.all_columns
), d2(s,e) AS (SELECT dt,DATEADD(MINUTE,@i,dt) FROM d1
), t AS
(
  SELECT [User],[Start Time],[End Time],
    StartInterval = DATEADD(MINUTE, DATEDIFF(MINUTE, 0, [Start Time])/@i*@i, 0),
    EndInterval   = DATEADD(MINUTE, DATEDIFF(MINUTE, 0, [End Time])/@i*@i, 0)
  FROM dbo.aTable -- WHERE?
),
n AS
(
  SELECT d2.s, d2.e, [User], [Start Time], [End Time],
    sr = CASE WHEN [Start Time] >= d2.s AND [Start Time] < d2.e THEN 1 END,
    er = CASE WHEN [End Time] > d2.s AND [End Time] <= d2.e THEN 1 END
   FROM d2 INNER JOIN t ON d2.s BETWEEN t.StartInterval AND t.EndInterval
 )
 SELECT [Interval From] = s, [Interval To] = e, [User],
   [Elapsed Time] = CASE WHEN sr = 1 OR er = 1 THEN
       DATEDIFF(MINUTE, CASE WHEN sr = 1 THEN [Start Time] ELSE s END,
       CASE WHEN er = 1 THEN [End Time] ELSE e END)
   WHEN s = [End Time] THEN 0 ELSE @i END
 FROM n ORDER BY [User], [Interval From];

A: Fun problem!  As Aaron mentions in his comment, a few things are ambiguous.  But I put together a script that could be used as a good starting point.  The script first identifies all possible 30 minute intervals, then matches user "events" to all matching intervals and does some date math to compute your elapsed times.  The script also attempts to handle a user being active multiple times within the same interval.  For your test inputs, the outputs match what you want.
If you expand to a larger data set, you may need to construct the final query more carefully to ensure that we only process the necessary intervals.  If you create a test script that has a larger volume of data and actually exhibits performance problems, I'd be happy to take a look at that in more detail.
-- Build the test data
CREATE TABLE #userEvents (
    userName VARCHAR(100) NOT NULL,
    elapsedTime AS CONVERT(VARCHAR, endTime-startTime, 108),
    startTime DATETIME NOT NULL,
    endTime DATETIME NOT NULL
)
GO
INSERT INTO #userEvents (userName, startTime, endTime)
VALUES ('User01', '07-02-2015 08:45', '07-02-2015 09:50')
GO

-- Create a table to hold all possible 30 minute intervals
CREATE TABLE #dailyIntervals (
    intervalStartTime DATETIME NOT NULL,
    intervalEndTime AS DATEADD(mi, 30, intervalStartTime),
    PRIMARY KEY (intervalStartTime)
)
GO

-- Determine the dates that the test data spans
-- This will be used build the possible 30 minute intervals
DECLARE @minDate DATE, @maxDate DATE, @numDays INT
SELECT  @minDate = CONVERT(DATE, MIN(startTime)),
        @maxDate = CONVERT(DATE, MAX(endTime)),
        @numDays = DATEDIFF(dd, @minDate, @maxDate) + 1
FROM #userEvents;

-- Build the full set of 30 minute intervals to be considered
WITH intervalMinutesIntoDay AS (
    -- Build starting # of minutes into the day for the 48 daily intervals of 30 minutes (0, 30, ..., 1410)
    SELECT TOP 48 30 * (ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1) AS startMinutes
    FROM master..spt_values
),
intervalStartDates AS (
    -- Build the dates (not including time component) that we need to consider
    SELECT TOP(@numDays) DATEADD(dd, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1, @minDate) AS startDate
    FROM master..spt_values
)
INSERT INTO #dailyIntervals (intervalStartTime)
SELECT DATEADD(mi, m.startMinutes, CONVERT(DATETIME, d.startDate)) AS intervalStartTime
FROM intervalStartDates d
CROSS JOIN intervalMinutesIntoDay m
GO

WITH userIntervals AS (
    -- For each user event, slot it into the proper intervals
    SELECT i.intervalStartTime,
            i.intervalEndTime,
            ue.userName,
            -- Start time is the user's startTime or, if the event started before this interval, the start of the interval
            CASE WHEN ue.startTime > i.intervalStartTime THEN ue.startTime ELSE i.intervalStartTime END AS userIntervalStartTime,
            -- End time is the user's entTime or, if the event ended after this interval, the end of the interval
            CASE WHEN ue.endTime < i.intervalEndTime THEN ue.endTime ELSE i.intervalEndTime END AS userIntervalEndTime
    FROM #dailyIntervals i
    JOIN #userEvents ue
        -- Detect whether user is active during some (or all) of the interval
        -- While it's a bit harder to read, the alternate option below may improve performance
        -- by allowing a seek to process only the necessary intervals
        ON ue.startTime <= i.intervalEndTime/*Alterate option: ON DATEADD(mi, -30, ue.startTime) <= i.intervalStartTime*/
        AND ue.endTime >= i.intervalStartTime
)
-- For each interval that the user event matched, compute the number of minutes the user was active during that interval
-- Note that we GROUP BY and SUM the data in case a user is active multiple times within the same interval
SELECT ui.intervalStartTime, ui.intervalEndTime, ui.userName,
    SUM(DATEDIFF(mi, userIntervalStartTime, userIntervalEndTime)) AS elapsedTimeInInterval
FROM userIntervals ui
GROUP BY ui.intervalStartTime, ui.intervalEndTime, ui.userName
GO

-- Cleanup
DROP TABLE #userEvents
GO
DROP TABLE #dailyIntervals
GO

A: Unfortunately, the starting point of your data makes this rather challenging. If it must be done at runtime, this is one possible solution:
-- Mimicing existing data

DECLARE @TableName TABLE ([User] VARCHAR(6), [Elapsed Time] VARCHAR(5), [Start Time] DATETIME, [End Time] DATETIME)

INSERT INTO @TableName VALUES ('User01', '01:05', '07-02-2015 08:45', '07-02-2015 09:50')

-- Setting up dateframe creation

DECLARE @mintime DATETIME = (SELECT MIN([Start Time]) FROM @TABLENAME),
        @maxtime DATETIME = (SELECT MAX([End Time]) FROM @TABLENAME)

DECLARE @i DATETIME =  DATEADD(MINUTE, (DATEPART(MINUTE, @mintime )/30) * 30, DATEADD(HOUR, DATEDIFF(HOUR, 0, @mintime), 0)),
        @tolastinterval DATETIME =  DATEADD(MINUTE, (DATEPART(MINUTE, @maxtime )/30) * 30, DATEADD(HOUR, DATEDIFF(HOUR, 0, @maxtime), 0))

DECLARE @dateframe TABLE (datetime DATETIME)

-- Populate DateFrame Table

WHILE @i <= @tolastinterval
BEGIN
    INSERT INTO @dateframe SELECT @i

    SET @i = DATEADD(MINUTE, 30, @i)
END

SELECT d.[datetime] [Interval From],
       DATEADD(MINUTE, 30, d.datetime) [Interval To],
       t.[User],
       '00:' + LEFT(CAST(MIN(
                    DATEDIFF(MINUTE,
                    CASE WHEN d.[datetime] < t.[Start Time] THEN t.[Start Time] ELSE d.[datetime] END,
                    CASE WHEN t.[End Time] < DATEADD(MINUTE, 30, d.datetime) THEN t.[End Time] ELSE DATEADD(MINUTE, 30, d.datetime) END
                    )) AS CHAR(2)) + '0', 2)
FROM @dateframe d
FULL OUTER JOIN @TABLENAME t
    ON 1=1
WHERE d.[datetime] <= t.[End Time]
    OR DATEADD(MINUTE, 30, d.datetime) >= t.[Start Time]
GROUP BY d.[datetime],
       t.[User]

Though it's horrible to look at.
If this is a common issue that you will want an ongoing solution to, another possible solution is to create a static dimension based on half hours and use that as the base, instead of dynamically creating the frame at runtime.
Also, this solution isn't robust enough to handle overlapping time entries for the same user- that would require another level of handling:
;WITH C1 AS
(
SELECT [user], [start time] AS ts, 1 AS type, ROW_NUMBER() OVER (ORDER BY [start time]) AS s, NULL AS e
FROM @TableName
UNION ALL
SELECT [user], [end time] AS ts, -1 AS type, NULL AS s, ROW_NUMBER() OVER (ORDER BY [end time]) AS e
FROM @TableName
),
C2 AS
(
SELECT C1.*, ROW_NUMBER() OVER (ORDER BY [user], ts, type DESC) AS se
FROM C1
),
C3 AS
(
SELECT [user],
       ts,
       FLOOR((ROW_NUMBER() OVER (ORDER BY ts) - 1) / 2 + 1) AS grpnum
       FROM C2
       WHERE COALESCE(s - (se - s) - 1, (se - e) - e) = 0
)

SELECT [user], MIN(ts) AS start_date, max(ts) AS end_date
FROM C3
GROUP BY [user], grpnum


text:
Q: Ansible: Intersection of two host groups using yaml inventory I have 2 groups, each with child groups called dev and test.  I am trying to target test hosts in group2 (four.example.com) using the pattern group2:&test.
Given the yaml inventory:
all:
  children:
    group1:
      children:
        dev:
          hosts:
            one.example.com:
        test:
          hosts:
            two.example.com:
    group2:
      children:
        dev:
          hosts:
            three.example.com:
        test:
          hosts:
            four.example.com:

And playbook:
- name: health check
  hosts: group2:&test
  tasks:
    - name: Ping hosts
      ping:

I am getting pings back from both two and four.
I expect pings from only four.
Although it's true that two is part of a group called test, it is not part of the group called group2, and I therefore would not expect to see it as part of the intersect.
It's as though it's doing a logical or (||), rather than a logical and (&&)
Is this a limitation of Ansible when using nested groups with non-unique child names?

A: Q: "Is this a limitation of Ansible when using nested groups with non-unique child names?"
A: Ansible by design doesn't store the inventory tree. This might seem a limitation. Quoting from  How variables are merged

By default variables are merged/flattened to the specific host before a play is run. This keeps Ansible focused on the Host and Task, so groups don't really survive outside of inventory and host matching.

Quoting from Inheriting variable values: group variables for groups of groups

Any host that is a member of a child group is automatically a member of the parent group.

There are 2 implications

*

*The patern 'group2:&test' is a self-contradiction. The group test contains hosts: two and four. You agree on this by having tried the intersection. Otherwise, the intersection wouldn't make sense. But the quoted statement says that members of test are automatically members of both group1 and group2. In other words, Ansible can't tell the difference between 1) the group test keeping all hosts and 2) the group test as a child of group1 or group2. As an example, the inventories below are equivalent to the inventory in the question

all:
  children:
    group1:
      children:
        dev:
          hosts:
            one.example.com:
            three.example.com:
        test:
          hosts:
            two.example.com:
            four.example.com:
    group2:
      children:
        dev:
        test:

all:
  children:
    dev:
      hosts:
        one.example.com:
        three.example.com:
    test:
      hosts:
        two.example.com:
        four.example.com:
    group1:
      children:
        dev:
        test:
    group2:
      children:
        dev:
        test:

*The nested groups with non-unique child names don't serve the purpose of this use-case. Try the inventory below instead

all:
  children:
    group1:
      hosts:
        one.example.com:
        two.example.com:
    group2:
      hosts:
        three.example.com:
        four.example.com:
    dev:
      hosts:
        one.example.com:
        three.example.com:
    test:
      hosts:
        two.example.com:
        four.example.com:

Notes

*

*There might be differences among the inventories in which order the groups_vars will be merged if used. See How variables are merged.


text:
Q: Select a radio button in all rows from a button click GTK+ python, PyGObject I have a an form with two boxes. The upper box and the down box. In the upper box I have two buttons. One button is Add Row and the button is Select Radio button A in all rows in the list box.
In the down box I have a Listbox with a multiple rows. All rows are similar, There are two radio buttons, A and B,  in each row. When ever you click on the Select Radio button, The A radio button on all rows should be selected.
How do I do that?
I don't want to show my code here because of copyright issues. but I believe there should be some method stating :
def on_button_click(self, button):
   self.Listbox.Row_all.Radio_button_A.checked()

I appriciate any help
UPDATE:
This is a part of my code.
        # Adding new row to the list

    self.row = Gtk.ListBoxRow()
    self.row.set_border_width(5)

    downBox_main = Gtk.HBox()
    downBox_main.set_halign(Gtk.Align.CENTER)

    videoIcon = Gio.ThemedIcon(name="audio-x-generic")
    videoImage = Gtk.Image.new_from_gicon(videoIcon, Gtk.IconSize.DIALOG)

    vbox_link_and_butons = Gtk.VBox()
    vbox_link_and_butons.set_border_width(5)

    link_entry = Gtk.Entry()
    link_entry.set_placeholder_text("Paste the video link here")

    quality_hbox = Gtk.HBox()

    btnsQuality = [("4320p"), ("2160p"), ("1440p"), ("1080p"), ("720p"), ("480p")]
    for buttonNames in btnsQuality:
        btn = Gtk.ToggleButton()
        btn.set_label(buttonNames)
        quality_hbox.pack_start(btn, False, False, 2)

    radiobtn_box = Gtk.VBox()
    radiobtn_box.set_valign(Gtk.Align.CENTER)

    rbVideo = Gtk.RadioButton.new_with_label_from_widget(None, "Video")
    rbAudio = Gtk.RadioButton.new_from_widget(rbVideo)
    rbAudio.set_label("Audio")

    btnDownload = Gtk.Button()
    download_icon = Gio.ThemedIcon(name="down")
    image = Gtk.Image.new_from_gicon(download_icon, Gtk.IconSize.BUTTON)
    btnDownload.add(image)

    downBox_main.pack_start(videoImage, False, False, 0)
    vbox_link_and_butons.pack_start(link_entry, True, True, 0)
    vbox_link_and_butons.pack_start(quality_hbox, True, True, 3)
    radiobtn_box.pack_start(rbVideo, False, True, 0)
    radiobtn_box.pack_start(rbAudio, False, True, 0)
    downBox_main.pack_start(vbox_link_and_butons, True, False, 8)
    downBox_main.pack_start(radiobtn_box, True, True, 0)
    downBox_main.pack_start(btnDownload, True, True, 3)
    self.row.add(downBox_main)
    self.downBox.add(self.row)
    self.downBox.show_all()

And I try to reach those those radio buttons in each row. There are many rows with same structure.

A: You have to loop over the buttons and call each button's checked method.


text:
Q: Updating status bar item legend causes memory complications I'm making an app for displaying CPU temperature on the status bar (continuously), and I'm running into a memory problem. Consider the following excerpts:
func statusBarInit() {
    statusBarItem = statusBar.statusItemWithLength(NSVariableStatusItemLength)
    statusBarItem.button?.title = "0"
}

// Function called through an NSTimer:
func updateTemperature() {
    var temperature = String(getTemperature())
    statusBarItem.button?.title = "\(temperature)" // Problem
// statusBarItem.button?.title = "Fixed string" // Problem too.
}

I create the timer from applicationDidFinishLaunching as:
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(AppDelegate.updateTemperature), userInfo: nil, repeats: true)

The problem is that the assignment to statusBarItem.button?.title causes increased memory use, rising by discrete steps of 300 KB every minute (stepwise, not continuously), which is evident from the Activity Monitor instrument and the Memory debug pane. However, the leak detection instrument doesn't detect any leaks.
I can tell that the fault is not caused by the getTemperature() function because if I set the statusBarItem.button?.title with a fixed string (and comment out the call to getTemperature()) the problem remains. With no string assignment at all to statusBarItem.button.title there's no problem.
Maybe the timer frequency (100) is too fast? Actually, the temperature sampling code works ok with the given period.
Other code looks like:
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    var statusBar = NSStatusBar.systemStatusBar()
    var statusBarItem : NSStatusItem = NSStatusItem()
    ...
}


text:
Q: How to read numbers from a file and measure the time it takes? I have a text file called 10.text that contains 10 large numbers. I want to read those numbers and store them in an array of size 10. Then i want to print out these nmbers and the time it takes to read the file.
Here is my attempt:
int main(int argc, const char * argv[]) {

int i;
clock_t start, end;
double cpu_time_used;
double TimeOfReadingFile;
FILE *myFile;
int readarr10[10];

start = clock();
myFile=fopen("10.txt" ,"r");

printf("SIZE 10\n");
printf("----------------\n");
for (i = 0; i < 10; i++)
    fscanf(myFile, "%d", &readarr10[i]);
end = clock();

 for (i=0; i<10; i++) {
            printf("%d  ",readarr10[i]);
            printf("\n");
        }
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
TimeOfReadingFile=cpu_time_used*pow(10, 9);
printf("time for reading the 10 file: %f\n",TimeOfReadingFile);

return 0;}

the problem is that when i run it i get zeros for all thr numbers and a zero for the time.
This code is part of a project i am working on and i cannot continue if i dont get it right!

A: Reading 10 numbers can be below the definition of clock. On my BSD system on a virtual machine, I had to loop more than 1000 times to begin to see something. With a loop of 1000000 times (read 10 integers, rewind file) I get (more or less 2.5 micro sec for the operation. If I include the fopen/fclose in the loop, I end at 24 micro sec.
I think (but I must acknowledge that I am not sure of it), that a rewind on a small FILE* only resets the file pointer but does not read again any sector from the disk. On the other hand, reading 10 integers (one single disk operation) should be short behind opening and closing a file.
So my conclusion is (on my system):

*

*file access: more or less 20 micro seconds

*decoding 10 integer: more of less 2 micro seconds.

I have a not too fast disk and the overhead on running a VirtualBox machine, so on high speed computers, times could even be smaller. So on one single iteration it is no surprise that end == start.


text:
Q: What is/are the algebraic equation(s) for transforming a unit square into a specific parallelogram? Goal: To transform a unit square into a parallelogram in which (a) the diagonals are parallel to the unit square's diagonals, (b) the longest diagonal is equal in length to either of the unit square's diagonals, and (c) the diagonals intersect at the midpoint of the longest diagonal.
Using basic algebra, not trigonometry or matrix format, what is/are the transformation equation(s)?

A: The matrix for the system is rooted in the basic algebraic form. If you labeled your vertices clockwise starting at the left top in the following way:
For the square:
$$(x_1,y_1),(x_2,y_2),(x_3,y_3),(x_4,y_4)$$
For the parallelogram:
$$(x'_1,y'_1),(x'_2,y'_2),(x'_3,y'_3),(x'_4,y'_4)$$
you would get the following system of equations:
$$a x_n + b y_n = x'_n $$
$$c x_n + d y_n = y'_n$$
For each vertex, where $n$ specifies the vertex and $a,b,c,d$ are the coefficients to be solved for.  Assuming the transforms are linear.


text:
Q: Get the max value one column but group on another In SQL Server I am trying to figure out how to get an entire row for the latest record of a user. I have a table where it's basically a log of all users who do an action and a date time. So for example

userId
action
datetime

1
jump
2022-01-01 07:50:00.000

2
run
2022-01-02 07:50:00.000

3
walk
2022-01-01 07:50:00.000

3
run
2022-01-04 07:50:00.000

4
jump
2022-01-01 07:50:00.000

2
walk
2022-01-01 07:50:00.000

1
walk
2022-01-01 01:50:00.000

1
walk
2022-01-03 04:50:00.000

4
run
2022-01-03 07:50:00.000

Basically I would want to query this table in order to return just the latest datetime rows for each unique user like this:

userId
action
datetime

1
walk
2022-01-03 04:50:00.000

2
run
2022-01-02 07:50:00.000

3
run
2022-01-04 07:50:00.000

4
run
2022-01-03 07:50:00.000

So far I tried doing this
select u.userid, u.action, u.datetime
from user_logs u
inner join (
    select userid, max(datetime) as datetime
    from user_logs
    group by userid
) tmp on tmp.userid = u.userid and tmp.datetime = u.datetime
order by u.userid

However this seems to still give me multiple rows with duplicate userids, different action statuses, but with all the same datetime now

A: Window function ROW_NUMBER() to the rescue.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (userId INT, action  VARCHAR(10), actionTime DATETIME)
INSERT INTO @tbl (userId, action, actionTime) VALUES
(1, 'jump', '2022-01-01 07:50:00.000'),
(2, 'run' , '2022-01-02 07:50:00.000'),
(3, 'walk', '2022-01-01 07:50:00.000'),
(3, 'run' , '2022-01-04 07:50:00.000'),
(4, 'jump', '2022-01-01 07:50:00.000'),
(2, 'walk', '2022-01-01 07:50:00.000'),
(1, 'walk', '2022-01-01 01:50:00.000'),
(1, 'walk', '2022-01-03 04:50:00.000'),
(4, 'run' , '2022-01-03 07:50:00.000');
-- DDL and sample data population, end

;WITH rs AS
(
    SELECT *
        , ROW_NUMBER() OVER (PARTITION BY userId ORDER BY actionTime DESC) AS seq
    FROM @tbl
)
SELECT *
FROM rs
WHERE seq = 1;

Output
+--------+--------+-------------------------+-----+
| userId | action |       actionTime        | seq |
+--------+--------+-------------------------+-----+
|      1 | walk   | 2022-01-03 04:50:00.000 |   1 |
|      2 | run    | 2022-01-02 07:50:00.000 |   1 |
|      3 | run    | 2022-01-04 07:50:00.000 |   1 |
|      4 | run    | 2022-01-03 07:50:00.000 |   1 |
+--------+--------+-------------------------+-----+

A: Typical case for window functions.
select userid, action, datetime
  from (select u.*,
               row_number() over (partition by userid order by datetime desc) rn
          from user_logs u) _
 where rn = 1

A: You can use ROW_NUMBER() to find the latest row for each user.
For example, you can do:
select *
from (
  select *,
    row_number() over(partition by userId order by datetime desc) as rn
  from user_logs
) x
where rn = 1


text:
Q: How do I unit test streaming download using jersey / dropwizard? I have a resource method which produces a streaming download:
@GET
@Path("/{assetId}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download(@PathParam("assetId") String assetId) {
    StreamingOutput stream = os -> service.download(assetId, os);
    return Response.ok(stream).build();
}

I want to unit test this with a mock service object. I already have:
private static AssetsService service = Mockito.mock(AssetsService.class);

@ClassRule
public final static ResourceTestRule resource = ResourceTestRule.builder()
    .addResource(new AssetsResource(service))
    .addProvider(MultiPartFeature.class)
    .build();

@Test
public void testDownload() {
    reset(service);
    // how to get an output stream from this?
    resource.client().target("/assets/123").request().get();
}

Per my comment in the test, what do I need to do in order to get an outputstream from the response? I find the jersey client API pretty confusing.
Once I have this, I'll stub the service call so that it writes a known file, and test that it's received correctly.

A: Try this:
Response response = resource.client().target("/assets/123").request().get();

InputStream is = response.readEntity(InputStream.class);


text:
Q: Google Maps API infowindow not recieving the value I have my webpage where in the map i have some markers loaded from a DB, these ones load correctly and i have an addListener('click') for each of these markers that opens a little window with infowindow.open(), the thing is that i want this window to load with the correct information from the element of the DB that corresponds to the marker i clicked, i've tried to pass the value in diferent ways and using diferent variables, but the only thing i get is undefined or the last element of the DB, and what i want is the information of the selected marker.
Code here:


text:
Q: With Open Liberty, how to use an environment variable as an application property? I expected to be able to do something like this in my server.xml, but I could not get it to work:
<variable name="my.ldap.url" value="${LDAP_URL}" />

Setting it in jvm.options or server.env do not seem to be options either from what I can tell. Neither of those are parsing environment variables from my tests.
-Dmy.ldap.url=$LDAP_URL

Setting properties in my own files and using environment variables did not seem to work either. I tried something like this in my server.xml
<library id="configs">
    <fileset dir="${server.config.dir}/configs" includes="*.properties" />
</library>

So I'm just lost for ideas right now. How do I take environment variables and inject them into an Open Liberty application as application properties?
I searched high and low for documentation on this, with no success.
In Jboss I was able to accomplish simple via
bin/standalone.sh -Dmy.ldap.url=$LDAP_URL

A: It should work for you exactly the way it does in Jboss:
wlp/bin/server start server1 -Dmy.ldap.url=$LDAP_URL
Your <variable> definition would create a Liberty configuration variable that resolves to the value of LDAP_URL in the environment, but it would not be set as a java system property.
If you're still seeing problems with passing the value on the command line you could check all java system properties by running:
wlp/bin/server dump {server name}
In the output zip file, the dump_{timestamp}/introspections/JavaRuntimeInformation.txt will show both the command line arguments and all defined java system properties.

A: I'd consider using Microprofile config, checkout this guide and see it does answer your questions.
It shows you how to inject variables using following schema:
@Inject @ConfigProperty(name="port")
private int port;

assuming there is PORT env entry in your system.
You can also use env variables in server configuration using server.xml for example:
<properties.db2.jcc serverName="${JDBC_HOST}" portNumber="${JDBC_PORT}" databaseName="${JDBC_DB}" sslConnection="${JDBC_SSL}"
            user="${JDBC_ID}" password="${JDBC_PASSWORD}"/>

Details here https://openliberty.io/docs/latest/reference/config/server-configuration-overview.html
For your library point you would have to add it to your application via classloader, so I wouldn't recommend that. Like this:
<application name="myapp" type="ear" location="myapp.ear">
  <classloader commonLibraryRef="configs" />
</application>

Hope it solves your problems.

A: The final answer I found to this, is you can inject environment variables into properties using the <appProperties> tag in your server.xml
Documentation is here
https://openliberty.io/guides/microprofile-config-intro.html#configuring-as-an-appproperties-element-scoped-by-application
A simple example of this using an environment variable looks like ...
<webApplication location="my.war" type="war">
  <appProperties>
     <property name="my.ldap.url" value="${LDAP_URL}"/>
  </appProperties>
</webApplication>


text:
Q: Exception similar to ModuleNotFoundError in Python 2.7? I'm trying to add some explicit exceptions to a piece of code, but the problem is that I have Python 3 and it has to be Python 2.7 compatible with the ModuleNotFoundError in Python 3. So any which exception is similar to that in Python 2.7?

A: Use ImportError. ModuleNotFoundError is a subclass of ImportError, and a very new one, having only been introduced in Python 3.6.
If you want to use ModuleNotFoundError when it's available and ImportError if it's not, you can make a feature check:
try:
    ModuleNotFoundError
except NameError:
    ModuleNotFoundError = ImportError

# later
raise ModuleNotFoundError(whatever_message)


text:
Q: How to get the value of hidden field in
* using jQuery? I place filname in a hidden input field in
 lable, I hope to get the value of hidden input field using jQuery, but the following code don't get the correct result, it return undefined value,   how can I do? Thanks!
Js
function GetHiddle() {

    $(".ActionClass").change(function () {
        var selectValue = $('.ActionClass').val();

        var fileName = GetHiddenFilename(this.parent);
        alert("My "+fileName);

        if (selectValue == "DoDelete") {

        }

        if (selectValue == "DoRename") {

        }
    });

}

function GetHiddenFilename(obj) {
    return $(obj).siblings("input[type='hidden']").val();
}

Html

                           <input type="hidden" value="/storage/emulated/0/Pictures/A1.PNG" />
                           <select class="ActionClass">
                             <option value="DoAction">Action</option>
                             <option value="DoDelete">Delete</option>
                             <option value="DoRename">Rename</option>
                             <option value="DoCopy">Copy</option>
                           </select>

                           <input type="hidden" value="/storage/emulated/0/Pictures/A2.PNG" />
                           <select class="ActionClass">
                             <option value="DoAction">Action</option>
                             <option value="DoDelete">Delete</option>
                             <option value="DoRename">Rename</option>
                             <option value="DoCopy">Copy</option>
                           </select>

A: Try as follows.
Use this instead of this.parent and prev for siblings.

$(document).ready(function() {
  function GetHiddle() {
    $(".ActionClass").change(function() {
      var selectValue = $(this).val();

      var fileName = GetHiddenFilename(this);
      alert("My " + fileName);

      if (selectValue == "DoDelete") {

      }

      if (selectValue == "DoRename") {

      }
    });
  }
  function GetHiddenFilename(obj) {
    return $(obj).prev().val();
  }

  GetHiddle();
});

    <input type="hidden" value="/storage/emulated/0/Pictures/A1.PNG" />
    <select class="ActionClass">
      <option value="DoAction">Action</option>
      <option value="DoDelete">Delete</option>
      <option value="DoRename">Rename</option>
      <option value="DoCopy">Copy</option>
     </select>

    <input type="hidden" value="/storage/emulated/0/Pictures/A2.PNG" />
    <select class="ActionClass">
      <option value="DoAction">Action</option>
      <option value="DoDelete">Delete</option>
      <option value="DoRename">Rename</option>
      <option value="DoCopy">Copy</option>
     </select>

A: There are a number of things wrong in your JavaScript.  First, you're not calling your GetHiddle() function (not sure if this is a typo, but I left the name as-is).  Second, using you use the parent function via a jQuery selector and as a method.  Finally, siblings() is the wrong function, since you want the descendants; find() is more appropriate.  Here are the fixes to make your JavaScript work.
function GetHiddle() {
$(".ActionClass").change(function () {
    var selectValue = $(this).val();

    var fileName = GetHiddenFilename($(this).parent());
    alert("My "+fileName);

    if (selectValue == "DoDelete") {
        // Do something
    }

    if (selectValue == "DoRename") {
        // Do something
    }
});

function GetHiddenFilename(obj) {
    return $(obj).find("input[type='hidden']").val();
}

GetHiddle();

A:
you can  simply use this all method
  $foo is id

alert($('input#foo').val());
alert($('input[name=zyx]').val());
alert($('input[type=hidden]').val());
alert($(':hidden#foo').val());
alert($('input:hidden[name=zyx]').val());


text:
Q: Cypher - return 1 'random' node from specific relationships Trying to build a Cypher query that returns ONE entry per 'comic'.
Basic structure is as follows:
(Comic)<-[]-(Media)-[]->(MediaType)

I want to grab 3 'random' comics and return only one Media per comic of said type. As a comic may have 100 medias of the media type, it's a little concerning. I could break this down into multiple queries, but I am sure there's a way for Cypher to do this through its own system.
My original code would do what it needed to, but if there were multiple medias of the same type, one comic would had the possibility of being returned multiple times.
The original Code:
MATCH (mt:MediaType{Name: {mediatype} })
<-[:Is_Media_Of]-(m:Media)-[:Is_Media_For]->(w:Webcomic)
WHERE w.ComicID <> toInt({comicid})
AND m.Status = 'Active'
RETURN m.URL as ImgURL,
w.Name as ComicName,
rand() as r
ORDER BY r ASC Limit toInt({count}) ",
["mediatype"=>$AdType,"count"=>$Count,"comicid"=>$ComicID])

This would sometimes return:
'comic1' 'img'
'comic2' 'img'
'comic1' 'img2'
'comic3' 'img2'
'comic4' 'img1'
'comic3' 'img5'

I'm sure it's pretty straight forward and I'm missing something. Any help is greatly appreciated.
Bruno's Code:
MATCH (mt:MediaType{Name: {mediatype}})
<-[:Is_Media_Of]-(m:Media)-[:Is_Media_For]->
(w:Webcomic) WHERE w.ComicID <> toInt({comicid})
AND m.Status = 'Active'
WITH distinct m, w
RETURN m.URL as ImgURL, w.Name as ComicName, rand() as r
ORDER BY r ASC Limit toInt({count})

Result for Bruno's Code:
ImgURL                       ComicName           r
"ms-rot-d1517513337.jpg"    "MoonSlayer"    0.09929832004330252
"ms-rot-b1517513245.jpg"    "MoonSlayer"    0.17924831869113889
"ms-rot-e1517513507.jpg"    "MoonSlayer"    0.23860836768580007
"mrRotator021516985058.jpg" "Mailbox Rocketship"    0.29152315193261946
"rotator1517004270.png" "Grapple Seed"  0.3167179880041201

Current results:

Wanted results:

A: Try it:
MATCH (mt:MediaType{Name: {mediatype}})<-[:Is_Media_Of]-(m:Media)-[:Is_Media_For]->(w:Webcomic)
WHERE w.ComicID <> toInt({comicid})
AND m.Status = 'Active'
WITH distinct w, mt, collect(m) as ms
RETURN ms[0].URL as ImgURL, w.Name as ComicName, rand() as r
ORDER BY r ASC Limit toInt({count})

I'm basically grouping by comic and collecting all medias into a list. Then I'm returning the first element of the list.


text:
Q: How can you add AMPscript to an asset URL in Einstein Content Selection? We use AMPscript to add our discount codes to our email URLs. We add something like this to the top of our emails:
%%[
Var @campaign, @pcode
Set @campaignID = "campaigncode"
Set @pcode = "123456789"
]%%

and the URLs within the email look like this:
www.website.com/website?utm_campaign=%%= v(@campaignID) =%%&pcode=%%= v(@pcode) =%%
We want to try using Einstein Content Selection for our secondary images but I am having trouble getting the campaignID and pcode dynamically added. In the Einstein Content Selection asset library, I added the URL like I do for the other links in the email:www.website.com/website?utm_campaign=%%= v(@campaignID) =%%&pcode=%%= v(@pcode) =%%
But when I insert the Einstein Content Selection content block and send the email, it doesn't add in the parameters from the top of the email and so the discount isn't added to the link. How can I do this?
Here is what the HTML is of the Einstein Content Selection block is:
%%[
/*
  Einstein Content Selection -- Modify At Your Own Risk
*/

VAR @subscriber_id, @subscriber_key, @mid, @mid_dash, @hash_subid, @hash_subkey, @hash_email
SET @subscriber_id = SubscriberID
SET @subscriber_key = lowercase(_subscriberkey)
SET @email = emailname_
SET @mid = memberid
SET @mid_dash = Concat(@mid, "-")
SET @hash_subid = SHA256(Concat(@mid_dash,@subscriber_id))
SET @hash_subkey = SHA256(Concat(@mid_dash,@subscriber_key))
SET @hash_email = SHA256(Concat(@mid_dash,@email))
IF EMPTY(@seed) THEN
  VAR @seed
  SET @seed = Format(now(), "ddHHmmss")
ENDIF
]%%

%%[
/*
  Einstein Content Selection -- End
*/
]%%

A: I'd suggest parameterizing your append variables:
In the init block:
%%[

set @campaignID = "campaigncode"
set @pcode = "123456789"

set @params1 = ""
set @params1 = concat(@params1, "utm_campaign=", @campaignID)
set @params1 = concat(@params1, "&pcode=", @pcode)

]%%

In the body:
link

I'd give the Einstein Content links the same treatment:
%%[

VAR @subscriber_id, @subscriber_key, @mid, @mid_dash, @hash_subid, @hash_subkey, @hash_email
SET @subscriber_id = SubscriberID
SET @subscriber_key = lowercase(_subscriberkey)
SET @email = emailname_
SET @mid = memberid
SET @mid_dash = Concat(@mid, "-")
SET @hash_subid = SHA256(Concat(@mid_dash,@subscriber_id))
SET @hash_subkey = SHA256(Concat(@mid_dash,@subscriber_key))
SET @hash_email = SHA256(Concat(@mid_dash,@email))

IF EMPTY(@seed) THEN
  VAR @seed
  SET @seed = Format(now(), "ddHHmmss")
ENDIF

set @params2 = ""
set @params2 = concat(@params2, @params1)
set @params2 = concat(@params2, "&subscriber_id=", @hash_subid)
set @params2 = concat(@params2, "&subscriber_key=", @hash_subkey)
set @params2 = concat(@params2, "&context=", _messagecontext)
set @params2 = concat(@params2, "&email=", @hash_email)
set @params2 = concat(@params2, "&job_id=" ,jobid)
set @params2 = concat(@params2, "&send_date=", xtyear, "-" , xtmonthnumeric, "-" , xtday)
set @params2 = concat(@params2, "&seed=", @seed)

set @params3 = ""
set @params3 = concat(@params3, @params2)
set @params3 = concat(@params2, "&image=true")

]%%

A: Nice work Adam!
Another option is to use Parameter Management within the Marketing Cloud if they are parameters that are used consistently.
As an exercise, I added a parameter called blurb and populated an AMPscript variable @blurb in the email and the parameter was passed through correctly with my Parameter Management Tracking String setup as:
utm_source=sfmc&utm_medium=email&utm_campaign=%%emailname_%%&utm_term=%%linkname%%&utm_id=%%jobid%%&sfmc_id=%%subscriberid%%&blurb=%%=v(@blurb)=%%
Note: I only added &blurb=%%=v(@blurb)=%% to the default.
Help doc: https://help.salesforce.com/articleView?id=sf.mc_overview_parameter_management.htm&type=5