text:
Q: Jquery - mouse over -> fade in/out // click -> opacity 100% // other click -> opacity 60 I'm working on a website with jquery and thumbnails.
When the page is loaded all the thumbnails have to be on 60% of opacity. As soon as you go with your mouse over a thumb it needs to fade to 100%, if you move with your mouse out the thumbnail needs to fade back up on 60% of opacity.
When the user clicks on a thumbnail it has to stay at 100% of opacity. As soon as the user clickss on another thumbnail the 'old' thumbnail has to fade back to 60% and the 'new' one has to stay at 100%. (it already has 100% opacity because you go with your mouse over it).
This is the code I have so far:
$(window).bind("load", function () {
    $("#mycarousel li").fadeTo(1, 0.6);

    $("#mycarousel li").hover(function () {
        $(this).fadeTo(350, 1.0);
        $(this).addClass('Active');
    }, function () {
        $("this:not('.Active')").fadeTo(350, 0.6);
    });
});

Any help would be appreciated.

A: $(window).bind("load", function() {
    var activeOpacity   = 1.0,
        inactiveOpacity = 0.6,
        fadeTime = 350,
        clickedClass = "selected",
        thumbs = "#mycarousel li";

    $(thumbs).fadeTo(1, inactiveOpacity);

    $(thumbs).hover(
        function(){
            $(this).fadeTo(fadeTime, activeOpacity);
        },
        function(){
            // Only fade out if the user hasn't clicked the thumb
            if(!$(this).hasClass(clickedClass)) {
                $(this).fadeTo(fadeTime, inactiveOpacity);
            }
        });
     $(thumbs).click(function() {
         // Remove selected class from any elements other than this
         var previous = $(thumbs + '.' + clickedClass).eq();
         var clicked = $(this);
         if(clicked !== previous) {
             previous.removeClass(clickedClass);
         }
         clicked.addClass(clickedClass).fadeTo(fadeTime, activeOpacity);
     });
});


text:
Q: Why is this code not deterministic? The following snippet is code from water-nsq benchmark from SPLASH 2...
    if (comp_last > NMOL1)
    {
        for (mol = StartMol[ProcID]; mol < NMOL; mol++)
        {
            pthread_mutex_lock(&gl->MolLock[mol % MAXLCKS]);

            for ( dir = XDIR; dir  <= ZDIR; dir++) {
                temp_p = VAR[mol].F[DEST][dir];
                temp_p[H1] += PFORCES[ProcID][mol][dir][H1];
                temp_p[O]  += PFORCES[ProcID][mol][dir][O];
                temp_p[H2] += PFORCES[ProcID][mol][dir][H2];
            }

            pthread_mutex_unlock(&gl->MolLock[mol % MAXLCKS]);
        }

        comp = comp_last % NMOL;
        for (mol = 0; ((mol <= comp) && (mol < StartMol[ProcID])); mol++)
        {
            pthread_mutex_lock(&gl->MolLock[mol % MAXLCKS]);

            for ( dir = XDIR; dir  <= ZDIR; dir++)
            {
                temp_p = VAR[mol].F[DEST][dir];
                temp_p[H1] += PFORCES[ProcID][mol][dir][H1];
                temp_p[O]  += PFORCES[ProcID][mol][dir][O];
                temp_p[H2] += PFORCES[ProcID][mol][dir][H2];
            }

            pthread_mutex_unlock(&gl->MolLock[mol % MAXLCKS]);
        }
    }
    else
    {
        for (mol = StartMol[ProcID]; mol <= comp_last; mol++)
        {
            pthread_mutex_lock(&gl->MolLock[mol % MAXLCKS]);

            for ( dir = XDIR; dir  <= ZDIR; dir++)
            {
                temp_p = VAR[mol].F[DEST][dir];
                temp_p[H1] += PFORCES[ProcID][mol][dir][H1];
                temp_p[O]  += PFORCES[ProcID][mol][dir][O];
                temp_p[H2] += PFORCES[ProcID][mol][dir][H2];
            }

            pthread_mutex_unlock(&gl->MolLock[mol % MAXLCKS]);
        }
    }

    pthread_barrier_wait(&(gl->start));

The problem is that it is not deterministic at the barrier in the end, that is, if you execute this code two times with same inputs, it gives different answers. In other words, if the lock order of mutexes is changed, the results are different.
And yes I have verified this by noting the memory pages. Also I can assure you that the change occurs in the VAR's (pointed by temp_p) memory.
I want to know why? Because apparently, all threads are putting their own values (PFORCES[ProcID]...) to the sum of temp_p and at the end, that is at the barrier, the results should be same, no matter the order in which threads acquired the locks.
[EDITED]
Also, please note that variables comp, dir and mol are all local variables of the thread and therefore not shared.

A: Second try.
I can't check it, but I assume that in temp_p[H1] += PFORCES[ProcID][mol][dir][H1]; you are adding doubles or floats.
For floating point types, the order of addition matters! Floating point addition is not associative!
A different thread order means a different addition order. So changes in the outcome are to be expected.
See http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems for some explanation.

A: I notice that you do not show the declaration of the loop variables, like mol and dir.
Could it be that the are accidently shared between threads?
If so, all kind of race conditions between e.g. one thread's mol++ and other thread's [mol % MAXLCKS] will cause problems.
UPDATE: According to the comments below, this does not seem to be the case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flutter / Firebase project - Is `Unhandled Exception: Null check operator used on a null value` causing a blank screen? I'm working on a flutter project with firebase. I'm currently developing on a MacBook, using a simulated iPhone (just in case this is relevant). I am able to run my app, but when doing so it's just a white blank screen that never goes away, it may also be pertinent to know this happens on the Chrome, and simulated Android devices too. Looking in the run window, I can see I have an error showing the following:
Launching lib/main.dart on iPhone 13 in debug mode...
Running Xcode build...
Xcode build done.                                           28.4s
Debug service listening on ws://127.0.0.1:61474/fF4XR-ozS5s=/ws
Syncing files to device iPhone 13...
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
#0      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:121:86)
#1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:146:36)
#2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
#3      MethodChannel.invokeListMethod (package:flutter/src/services/platform_channel.dart:342:41)
#4      MethodChannelFirebase._initializeCore (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:31:37)
#5      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:73:13)
#6      Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:47)
#7      main (package:we_rise/main.dart:8:18)
#8      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:145:25)
#9      _rootRun (dart:async/zon<…>

Since I'm still quite a novice, I can't quite decipher what has gone wrong, or what I'm looking at here. Please find below my main.dart file code:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'database_config.dart';
import 'launch_page.dart';

void main() async {
  await Firebase.initializeApp(
    options: FirebaseOptions(
        apiKey: "foo",//"apiKey",
        appId: "foo",//"appId",
        messagingSenderId: "foo",//"messagingSenderId",
        projectId: "foo"),//"projectId"),
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown],
    );
    return MaterialApp(
      theme: ThemeData(
        brightness: Brightness.light,
        fontFamily: 'BookmanOldStyle',
      ),
      home: LaunchPage(),
    );
  }
}

I hope this is useful. I truly do not understand why it's presenting me with a blank white screen when the app loads. I also read this answer, but I don't think I've used a null check operator in my code. Any help, advice, and criticism is appreciated.
EDIT: ADDED FLUTTER DOCTOR OUTPUT
flutter doctor output:
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.5.3, on macOS 12.0.1 21A559 darwin-arm, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] Connected device (2 available)

• No issues found!

flutter doctor -v output:
flutter doctor -v
[✓] Flutter (Channel stable, 2.5.3, on macOS 12.0.1 21A559 darwin-arm, locale en-GB)
    • Flutter version 2.5.3 at /Users/me/Documents/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 18116933e7 (3 months ago), 2021-10-15 10:46:35 -0700
    • Engine revision d3ea636dc5
    • Dart version 2.14.4

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /Users/me/Library/Android/sdk
    • Platform android-31, build-tools 31.0.0
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 13.2.1, Build version 13C100
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2020.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[✓] Connected device (2 available)
    • iPhone 13 (mobile) • C0D4EC95-07AF-46AB-A35E-F2B9F4437875 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-15-2 (simulator)
    • Chrome (web)       • chrome                               • web-javascript • Google Chrome 97.0.4692.71

• No issues found!

A: You should add the

WidgetsFlutterBinding.ensureInitialized()

to the main function before Firebase initialization.
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: FirebaseOptions(
        apiKey: "foo",//"apiKey",
        appId: "foo",//"appId",
        messagingSenderId: "foo",//"messagingSenderId",
        projectId: "foo"),//"projectId"),
  );
  await DatabaseConfig.initFirebase();
  runApp(MyApp());
}

A: I think one of these should work.

*

*Make sure you have initialized firebase properly i.e. right steps taken to integrate firebase with your project, flutterfire configure

*Add a name in the Firebase.initializeApp-
 await Firebase.initializeApp(

    name: "SecondaryApp",//**Add this line**
    options: FirebaseOptions(
        apiKey: "foo",//"apiKey",
        appId: "foo",//"appId",
        messagingSenderId: "foo",//"messagingSenderId",
        projectId: "foo"),
  );

A: For good measure, try a "flutter upgrade", since 2.5.3 is no longer the latest stable version, they're on 2.8.1 now. Then make sure you followed all of the instructions (to the letter) under each of the platform setup sections listed here.
If you've had to run "flutter clean" at any point or deleted your build folders, make sure you check them for the required includes as specified in that link above. I saw in the original post you said that flutterfire was not working on any of your platforms, which to me indicates that the library might not be fully configured under the build folders for each platform.

A: To all those who come across this issue, what worked for me was creating a new project on the Windows version (I'm using android studio) and remaking the program on there, you can even copy and paste for the most part.
It seems to me that the main issue was that I do not own an iPhone while developing on MacOS, and consequently, I was unable to run this while it's linked to my developer profile.


text:
Q: Counting number of maximal ideals with given property? There's a small theorem in algebra that I've been toying with. Let $R$ be integrally closed in its quotient field, and $E$ a splitting extension of the quotient field, and $S$ be the integral closure of $R$ in $E$. Then for a maximal ideal $p$ of $R$, there are only finitely many maximal ideals of $S$ whose intersection with $R$ is precisely $p$.
I was trying to formulate a small example. Let $f(X)=X^3+X+1$, and $E\supseteq\mathbb{Q}$ a splitting extension for $f$. So taking $R=\mathbb{Z}$ in this case, let $S$ be the integral closure of $\mathbb{Z}$ in $E$. I choose say $(3)$ as a maximal ideal of $\mathbb{Z}$. So there must be finitely many maximal ideals $q$ of $S$ such that $q\cap\mathbb{Z}=(3)$.
This sparked my curiosity, if we know that there are only finitely many such maximal ideals $q$, how many are there actually, at least in this case? I couldn't think of a way to actually enumerate them all to be able to say "There are 9 such maximal ideals!," or something along those lines. Thank you kindly.

A: Let  $R$ be a noetherian ring with fraction field $K=Frac(R)$.
 Let $K\subset E$ be a finite separable extension field of dimension $[E:K]=n$ and let $S$ be the integral closure of $R$ in $E$: it is also a Dedekind ring.
Now given a non-zero prime $\mathfrak p\subset R$, decompose the extended ideal  $\mathfrak p\cdot S\subset S$ as :
$$\mathfrak p\cdot S=\Pi \mathfrak P^{e_\mathfrak P}$$
(you can do that, since $S$ is Dedekind)
You then have the fundamental formula
$$n=\Sigma  e_{\mathfrak P } \cdot f_ {\mathfrak P}   $$
where $f_ {\mathfrak P}=[S/\mathfrak P:R/\mathfrak p]$.
The $\mathfrak P$'s in the above formulae are exactly the primes of $S$ over $\mathfrak p$ and there are thus at most $n$ of them. This is the bound you were looking for.
In your example, the splitting field $E$ of $X^3+X+1$ over $\mathbb Q$ has dimension 6 over $\mathbb Q$ and so you have at most 6 prime ideals over the prime ideal $\mathfrak p = (3)$ .
Bibliography J.-P. Serre, Local Fields, Chapter 1, §4.


text:
Q: Prevent email clients from creating calendar links in messages I am sending an email messages from a PHP script and some email clients parse date strings within the message and create clickable calendar "links". One example is Airmail for OSX. I am sure there are many others that do the same. I see 2 problems with this:

*

*The links are shown even though they actually don't exist

*I can't style them. Actually, I don't even know if they are going to be created and where.

*Anchor CSS rules are not respected for those links and they usually end up very ugly.

My current workaround is date('Y-m-d'), but honestly this is some ugly code and I am not even sure if it works with all email clients.
I am looking for a reliable way to make sure that dates are displayed properly (meaning: the way I created them) everywhere.

A:
My current workaround is date('Y-m-d'), but honestly
  this is some ugly code and I am not even sure if it works with all
  email clients.

What you have used above is zero width space to remove the linking on a device. I have tested the following in Litmus:
20/02/2018

20/02/2018

Here is a litmus link to show how it looks:
https://litmus.com/checklist/emails/public/cd94368
As you said the above is ugly (but gets the job done) and you are looking for alternatives, then below are different ways to do this for different email clients.
Fix Blue Links in Gmail
When Gmail spots an address or phone number in an email, it automatically adds an extra style declaration, which formats any link in the email that has no inline styles attached to it, as blue:
.ii a[href] { color: #15c; }

Option 1 (link per link basis):
HTML:
675 Massachusetts Ave.
Cambridge, MA 02139, USA

CSS:
.contact a {color:#000000!important; text-decoration:underline!important;}

Option 2 (All links in Gmail):
u + #body a {
    color: inherit;
    text-decoration: none;
    font-size: inherit;
    font-family: inherit;
    font-weight: inherit;
    line-height: inherit;
}

Source
Fix links in iOS
Option 1 (using meta tag):
<meta content="telephone=no" name="format-detection">

Option 2:
Use Zero width non joiner as the first tested answer above
Option 3:
Style it like the email text or give it another color:
a[href^=tel]{ color:#F00; text-decoration:none;}

Option 4:
On iOS devices an attribute is injected into the link which is detected to be an address, phone number, or dates. If you took a look at the source code of an email in Apple Mail on an iPhone, you would see something like this:

Using this attribute you can style all automatically linked text in a style declaration, inside your  block:
a[x-apple-data-detectors] {
    color: inherit !important;
    text-decoration: none !important;
    font-size: inherit !important;
    font-family: inherit !important;
    font-weight: inherit !important;
    line-height: inherit !important;
}

Source
I know thats a lot to take in but all options work and its just a matter of picking the right one for your job.
Let me know if you have any questions.


text:
Q: Дискорд бот на python, упоминание ролей Подскажите, как упомянуть роль через бота в дискорде?
await message.channel.send("@admin")

Вот такой код не работает.

A: 1. Способ:
Что бы упомянуть роль достаточно знать её ID и отправить сообщение с таким содержанием:
await message.channel.send("<@&id_роли>")

2. Способ:
Получить роль и упомянуть её:
from discord.ext import commands

@commands.command()
async def push(ctx: commands.Context):
    # Получаем роль
    role = ctx.guild.get_role(role_id=id_роли)
    # Отправляем сообщение
    await ctx.send(f"Роль: {role.mention}")

Если у вас уже имеется ID, то смысла получать роль нет, если в дальнейшем вы ничего не будете с ней делать.


text:
Q: How to get CosmosDB Emulator to automatically start upon machine startup / reboot We are trying to use Azure Storage Emulator and Azure CosmosDB Emulator for our local development as well as unit testing as part of CI / CD builds. Here is the main link with details on these emulators:
https://learn.microsoft.com/en-us/azure/cosmos-db/local-emulator
As part of this effort, we need some way to start and stop both the emulators. We have tried running on Docker, but it has its own issues due to anti-virus interventions etc, so I don't want to talk about that option in this post.
This is our main requirement - to start the emulators during machine reboot / startup. We were able to get this working in case of Azure Storage Emulator just by calling the appropriate command to start the emulator via Windows Task Scheduler, it was super easy. So we tried the same approach with CosmosDB Emulator, but it just fails with "Catastrophic failure (0x8000FFFF)" error without much details to troubleshoot the problem. This is on a Windows Server 2016 Standard machine, but I get the same result on my Windows 10 Enterprise machine as well.
Since then I tried few other options as below:

*

*Created a batch file with below command and run it via task scheduler:
start /d "C:\Program Files\Azure Cosmos DB Emulator" CosmosDB.Emulator.exe

This works when I manually run the batch file, but not via task scheduler.

*Same approach using PowerShell and same results as above.

*Finally I created a windows service using Topshelf which again works when running using visual studio or debugging code, but not when I install the service and run it within services console.
We have tried with different user accounts, using ones with admin rights as well. I had missed to add the below detail in my original post:
The CosmosDB emulator will start if run manually by either me or my team members, but when it is invoked by the task scheduler the following error is written to the system log
The application-specific permission settings do not grant Local Activation permission for the COM Server application with CLSID
 {D63B10C5-BB46-4990-A94F-xxxxxxxxxxxx}
  and APPID
 {9CA88EE3-ACB7-47C8-AFC4-xxxxxxxxxxxx}
  to the user {Damain}{UserName} SID (S-1-5-21-174494438-4207865126-xxxxxxxxx-xxxxx) from address LocalHost (Using LRPC) running in the application container Unavailable SID (Unavailable). This security permission can be modified using the Component Services administrative tool.
Is there any other option to get this working?

A: Posting the answer from David Noble below just so others can make use of it:
GitHub issue #7990
Please allow me to introduce myself. I'm dev owner of the Cosmos DB Emulator. Thanks for writing.
To start the Emulator via the task scheduler, try using this command line option: /noui. Please also ensure that the task runs with highest privileges under an account that belongs to the Administrators group.
I defined such a task just now that runs when I log in to my Windows 10 dev box. It runs this command line under my domain account which belongs to the local Administrators group:
"C:\Program Files\Azure Cosmos DB Emulator\CosmosDB.Emulator.exe" /noui
I confirmed that when I ran this task:
•Without the /noui option I saw the error you saw: E_UNEXPECTED (0x8000FFFF), Catastrophic failure.
•With the /noui option, the Emulator started correctly (without the task bar icon and without opening the data explorer as expected) and that I could use the data explorer to create documents.
Please give this a try and let us know how it goes. I'm here to help, if need be.

A: I did it by opening the file location of the CosmosDB shortcut on the start menu, copying the shortcut in that folder and pasting it to:
C:\Users\<user name>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

The UI works as expected.


text:
Q: Output of a column to only have two decimal numbers? I'm showing the query output on a default ViewGrid on a VB.NET web application and some of the output values give me 4 decimal values while I only need two decimal values do to the result for showing a currency.
How can I specify in the query to only show me a maximum of two decimal values for the values of D.ORIG_PRC and D.DISC_AMT?
My Query
 SELECT H.Emp_ID, H.Cust_ID, H.Rgst_ID, D.TRAN_LN_NUM, D.DISC_CD, D.AUTH_EMP_ID, D.ORIG_PRC, D.DISC_AMT, D.DISC_PCT, D.GL_ACCT_ID
 FROM Transaction_Header H
 INNER Join LN_Detail L ON (H.Str_ID = L.Str_ID And H.Rgst_ID = L.Rgst_ID And H.Tran_ID = L.Tran_ID)
 INNER Join LN_Discount D ON (L.Str_ID = D.Str_ID And L.Rgst_ID = D.Rgst_ID And L.Tran_ID = D.Tran_ID And L.Tran_LN_Num = D.Tran_LN_Num)
 WHERE(H.Str_ID = @Str_ID)
    And (H.Tran_ID = @Tran_ID)
    And ((H.Rgst_ID = @Rgst_ID) Or (@Rgst_ID Is NULL Or @Rgst_ID = ''))


text:
Q: how to get values from the array with the help of for loop In my ios app,
i have some data in one array,now i want to print that data with the help of NSlog in viewdidload , but i want to show that data inside one for loop...so i didn't get what should be my for loop.
i want to get values from the array with the help of using for...loop... how can i do that ?
storedDataArray = [[NSMutableArray alloc]init];

[storedDataArray addObject:@"Kaushal"];

[storedDataArray addObject:@"Bhaumik"];

[storedDataArray addObject:@"Arpit"];

[storedDataArray addObject:@"Swapnil"];

[storedDataArray addObject:@"Megha"];

[storedDataArray addObject:@"Ravi"];

for (int i=0; i<=6; i++) {
    NSLog(@"hello %d",storedDataArray);
}

A: is not
for (int i=0; i<=6; i++) {
NSLog(@"hello %d",storedDataArray);
}

it is
for (int i=0; i<storedDataArray.count; i++) {
NSLog(@"hello %@",storedDataArray[i]);
}

fast enumration
for (NSString *name in storedDataArray) {
NSLog(@"hello %@",name);
}

A: You have to add index in storedDataArray
for (int i=0; i<storedDataArray.count; i++) {
    NSLog(@"hello %@",storedDataArray[i]);
}

Or you can do without index
for (NSString *str in storedDataArray) {
    NSLog(@"hello %@",str);
}


text:
Q: Getting the sum of a float of numbers? I have 0.0 24.0 0.0 12.0 0.0 0.0 0.0 0.0 0.0 how do i get the sum of these values? .sum etc do not work on floats
EDIT:
Im doing
<% @data.each do |data| %>
    <%= data[ :values ]%>
<%end%>

Where data[:values] prints
[5.0, 0.0, 0.0, 0.0, 0.0]
[4.0, 0.0, 0.0, 0.0, 0.0]
[1.0, 0.0, 0.0, 0.0, 0.0]
and i only want to get the first value of each array and sum them together to get 10.0
@data prints
[{:name=>"BMW", :values=>[0.0, 0.0, 0.0, 0.0, 0.0]}, {:name=>"Asda", :values=>[32.0, 12.0, 0.0, 0.0, 0.0]}]

A: Assuming they are in an array, this works:
irb(main):001:0> [0.0, 1.0, 3.0].inject(:+)
=> 4.0

Edit: from your edited question, it appears you want:
@data.reduce(0) { |sum, x| sum += x[:values][0] }

Which grabs the first (0th) element of each :values, and sums them all together:
irb(main):003:0> @data
=> [{:values=>[0.0, 0.0, 0.0, 0.0, 0.0], :name=>"BMW"}, {:values=>[32.0, 12.0, 0.0, 0.0, 0.0], :name=>"Asda"}]
irb(main):004:0> @data.reduce(0) { |sum, x| sum += x[:values][0] }
=> 32.0

A: Here:
irb(main):001:0> values = [[1.0,0.0],[2.0,0.0],[3.0,0.0]]
=> [[1.0, 0.0], [2.0, 0.0], [3.0, 0.0]]
irb(main):002:0> values.map(&:first)
=> [1.0, 2.0, 3.0]
irb(main):003:0> values.map(&:first).inject(:+)
=> 6.0

Revised:
@data.map {|hash| hash[:values].first}.inject(:+)

A: If you have array of them:
[0.0, 24.0, 0.0, 12.0, 0.0, 0.0, 0.0, 0.0, 0.0].reduce(:+)

If not - use +.
0.0 + 24.0 + 0.0 + 12.0 + 0.0 + 0.0 + 0.0 + 0.0 + 0.0

=> 36.0
Or i miss something?

A: Do you need to get the sum in some fancy way, or is it okay to do it in a loop?
I would do it like the following:
sum = 0
array.each do |a|
  sum+=a
end


text:
Q: building otool on my mac gives Undefined symbols for architecture x86_64 So I downloaded otool from apple open source website:
https://opensource.apple.com/tarballs/cctools/cctools-895.tar.gz
Then I use CLion (an IDE) open otool and try to build it. CLion seems generates a CMakeLists.txt for me, and when I click build, it says:
[ 89%] Building C object CMakeFiles/otool.dir/print_objc2_64bit.c.o
[ 94%] Building C object CMakeFiles/otool.dir/sparc_disasm.c.o
[100%] Linking C executable otool
Undefined symbols for architecture x86_64:
  "_SWAP_DOUBLE", referenced from:
      _print_ef in m68k_disasm.c.o
      _print_literal8_section in ofile_print.c.o
      _print_literal_pointer_section in ofile_print.c.o
  "_SWAP_FLOAT", referenced from:
      _print_insn_neon in arm_disasm.c.o
      _print_ef in m68k_disasm.c.o
      _print_literal4_section in ofile_print.c.o
  "_SWAP_LONG_LONG", referenced from:
      _guess_pointer_pointer in arm64_disasm.c.o
      _guess_pointer_pointer in i386_disasm.c.o
      _print_library_toc in ofile_print.c.o
      _print_literal_pointer_section in ofile_print.c.o
      _print_init_term_pointer_section in ofile_print.c.o
      _walk_pointer_list in print_objc2_64bit.c.o
      _swap_cfstring_t in print_objc2_64bit.c.o
      ...
  "_allocate", referenced from:
      _method_reference in arm64_disasm.c.o
      _get_dyld_bind_info in dyld_bind_info.c.o
      _method_reference in i386_disasm.c.o
      _main in main.c.o
      _processor in main.c.o
      _setup_dyld_bind_info in main.c.o
      _print_text in main.c.o
      ...
  "_apple_version", referenced from:
      _main in main.c.o
      _version in main.c.o
  "_arch_usage", referenced from:
      _main in main.c.o
  "_assemble_12", referenced from:
      _hppa_disassemble in hppa_disasm.c.o
  "_assemble_17", referenced from:
      _hppa_disassemble in hppa_disasm.c.o
  "_assemble_21", referenced from:
      _hppa_disassemble in hppa_disasm.c.o
  "_assemble_3", referenced from:
      _hppa_disassemble in hppa_disasm.c.o
  "_error", referenced from:
      _main in main.c.o
      _print_bitcode_section in print_bitcode.c.o
      _print_xar_files_summary in print_bitcode.c.o
  "_error_with_arch", referenced from:
      _print_library_toc in ofile_print.c.o
      _print_sysv_library_toc in ofile_print.c.o
  "_errors", referenced from:
      _main in main.c.o
  "_get_arch_from_flag", referenced from:
      _main in main.c.o
  "_get_host_byte_sex", referenced from:
      _arm64_disassemble in arm64_disasm.c.o
      _guess_pointer_pointer in arm64_disasm.c.o
      _guess_cstring_pointer in arm64_disasm.c.o
      _guess_literal_pointer in arm_disasm.c.o
      _guess_cstring_pointer in arm_disasm.c.o
      _print_insn_neon in arm_disasm.c.o
      _print_coff_reloc_section in coff_print.c.o
      ...
  "_get_stack_addr_from_flag", referenced from:
      _print_argstrings in main.c.o
  "_get_toc_byte_sex", referenced from:
      _processor in main.c.o
  "_guess_short_name", referenced from:
      _setup_dyld_bind_info in main.c.o
      _print_hints in ofile_print.c.o
  "_llvm_create_disasm", referenced from:
      _create_arm64_llvm_disassembler in arm64_disasm.c.o
      _create_arm_llvm_disassembler in arm_disasm.c.o
      _create_thumb_llvm_disassembler in arm_disasm.c.o
      _create_i386_llvm_disassembler in i386_disasm.c.o
      _create_x86_64_llvm_disassembler in i386_disasm.c.o
  "_llvm_disasm_dispose", referenced from:
      _delete_arm64_llvm_disassembler in arm64_disasm.c.o
      _delete_arm_llvm_disassembler in arm_disasm.c.o
      _delete_thumb_llvm_disassembler in arm_disasm.c.o
      _delete_i386_llvm_disassembler in i386_disasm.c.o
      _delete_x86_64_llvm_disassembler in i386_disasm.c.o
  "_llvm_disasm_instruction", referenced from:
      _arm64_disassemble in arm64_disasm.c.o
      _print_insn in arm_disasm.c.o
      _i386_disassemble in i386_disasm.c.o
  "_llvm_disasm_set_options", referenced from:
      _print_text in main.c.o
  "_llvm_disasm_version_string", referenced from:
      _main in main.c.o
  "_low_sign_ext", referenced from:
      _hppa_disassemble in hppa_disasm.c.o
  "_makestr", referenced from:
      _print_bitcode_section in print_bitcode.c.o
  "_ofile_process", referenced from:
      _main in main.c.o
  "_reallocate", referenced from:
      _main in main.c.o
      _print_text in main.c.o
      _print_reloc in ofile_print.c.o
      _print_indirect_symbols in ofile_print.c.o
      _print_hints in ofile_print.c.o
      _print_literal_pointer_section in ofile_print.c.o
      _get_objc_sections in print_objc.c.o
      ...
  "_reloc_has_pair", referenced from:
      _get_symbol_32 in print_objc2_32bit.c.o
      _get_symbol_64 in print_objc2_64bit.c.o
  "_sign_ext", referenced from:
      _hppa_disassemble in hppa_disasm.c.o
      _print_immediate in hppa_disasm.c.o
  "_size_ar_name", referenced from:
      _print_ar_hdr in ofile_print.c.o
  "_swap_arm_thread_state64_t", referenced from:
      _print_thread_states in ofile_print.c.o
  "_swap_arm_thread_state_t", referenced from:
      _print_thread_states in ofile_print.c.o
  "_swap_base_relocation_block_header", referenced from:
      _print_coff_reloc_section in coff_print.c.o
  "_swap_base_relocation_entry", referenced from:
      _print_coff_reloc_section in coff_print.c.o
  "_swap_data_in_code_entry", referenced from:
      _processor in main.c.o
  "_swap_ppc_thread_state64_t", referenced from:
      _print_thread_states in ofile_print.c.o
  "_swap_twolevel_hint", referenced from:
      _processor in main.c.o
  "_swap_xar_header", referenced from:
      _print_bitcode_section in print_bitcode.c.o
  "_system_error", referenced from:
      _print_bitcode_section in print_bitcode.c.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [otool] Error 1
make[2]: *** [CMakeFiles/otool.dir/all] Error 2
make[1]: *** [CMakeFiles/otool.dir/rule] Error 2
make: *** [otool] Error 2

Here's the CMakeLists.txt:
cmake_minimum_required(VERSION 3.8)
project(otool)
include_directories( ../include )
set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES
        arm64_disasm.c
        arm64_disasm.h
        arm_disasm.c
        arm_disasm.h
        coff_print.c
        cxa_demangle.h
        dyld_bind_info.c
        dyld_bind_info.h
        hppa_disasm.c
        hppa_disasm.h
        i386_disasm.c
        i386_disasm.h
        i860_disasm.c
        i860_disasm.h
        m68k_disasm.c
        m68k_disasm.h
        m88k_disasm.c
        m88k_disasm.h
        main.c
        notify.c
        notify.h
        ofile_print.c
        ofile_print.h
        otool.h
        ppc_disasm.c
        ppc_disasm.h
        print_bitcode.c
        print_objc.c
        print_objc2_32bit.c
        print_objc2_64bit.c
        sparc_disasm.c
        sparc_disasm.h)

add_executable(otool ${SOURCE_FILES})

I don't know CMake a lot, how can I fix it? Specifically, how do I know which lib is causing the problem, and how do I add them into the CMakeLists? Thanks!


text:
Q: UIPopoverController display in wrong location I am switching views within the window. The orientation is sometimes confused.
Within one of the windows, when I attempt to display a popover which should be attached to a toolbar button, it is displayed in the location on the screen. If I physically change the orientation of the device, the popover is redraw in the correct location. If I switch it back again, it is drawn in the correct location. If I dismiss the popover and try to display it again, it again displays in the wrong location.
Suggestions appreciated.

A: Here when you display the popover controller from the view, first you need to check which orinetation you have now and based on the orientation you can choose the frame and open the popover controller from the current view. You can do like as follows:
    if(UIAppDelegate.intOrientation == 1)
    {
        popoverController.popoverContentSize = CGSizeMake(570, 720);
        [self.popoverController presentPopoverFromRect:CGRectMake(100, 150, 570, 720) inView:self.view permittedArrowDirections:NO animated:YES];
    }
    else
    {
        popoverController.popoverContentSize = CGSizeMake(820, 500);
        [self.popoverController presentPopoverFromRect:CGRectMake(102, 135, 820, 500) inView:self.view permittedArrowDirections:NO animated:YES];
    }

A: Problem went away, not sure why. I had opened an issue with Apple developer support. They looked through my code and came up with a couple of undocumented guidelines.
One was not to mix screen orientations between views being switched. Have them all consistently support landscape or not, portrait or not.
They also said that only one controller should be managing the screen at a time.
This issue came up with iOS4.2 on an iPad. Don't know if this applies anymore.


text:
Q: How do I split text file without delimiter into a list of dictionaries in python3? I have a text file that has data in the following shape:
{"id": 1, {"device_data": 123}, "created_at": "2020-04-03"}{"id": 2, {"device_data": 123}, "created_at": '2020-04-03'}{"id": 2, {"device_data": 123}, "created_at": "2020-04-03"}{"id": 2, {"device_data": 123}, "created_at": '2020-04-03'}

There aren't any \n delimiters or , delimiters that I can use here. I'd like to parse this into a list of dictionaries in order to load the data into a dataframe.
I've tried parsing this using .split() and list comprehension doing something like this:
lst = [x + '}' for x in data.split('}') if x != '']

But this obviously breaks for records that have nested objects.
I also tried doing this with regex but I'm struggling to figure out the appropriate way.  This is what I have so far:
re.split('(\{(.*)\})', data)

Per the suggestions below, I also attempted making use of the json library.
with open('path/to/file', 'r') as f:
    res = json.load(f)

However, this resulted in an error with the following message: JSONDecodeError: Extra data. I believe this is due to the fact that there are multiple valid jsons in this file.
I wanted to use the json.load() command with a for loop, but then I ran into trouble figuring out how to properly split the file contents.
Does anyone have a suggestion for how to approach this kind of problem?

A: Regex does not handle nested formats like this effectively.
This looks a bit like JSON, and Python has the builtin json package, which could help. To use it on this data, you'll need to first convert single quotes to double quotes: data_string.replace("'", '"'). But the format is probably still different enough from JSON to be a problem.
If you know what generated the data, that may help you figure out what will parse the data. Otherwise, this answer explains how to parse nested expressions manually.

A: Your data sort of looks like JSON, but with single instead of double quotes.
If that is the case, I would first suggest changing your data (if possible) to just use valid json, and then you can easily do:
myfile.json:
{ "foo": 42 }

import json

with open('myfile.json') as f:
  obj = json.load(f)

print(obj) # {'foo': 42}

Then obj is a valid python dictionary you can use as normal.
If you can't use double-quoted JSON, you could possibly refer to this question about parsing single-quoted JSON.

A: Your record separator is:
}{

so given
txt="{'id': 1, {'device_data': 123}, 'created_at': '2020-04-03'}{'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'}{'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'}{'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'}"

split into records with:
records=txt.split('}{')

The results look like:
records[0]="{'id': 1, {'device_data': 123}, 'created_at': '2020-04-03'"
records[1]="'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'"

and parse the records into dictionary's with
mydictlist = []
for record in records:
    # clean up excess brackets and tokens
    record = record.replace('{','').replace('}','').replace("'",'')
    mydict = dict((k.strip(), v.strip()) for k,v in
          (item.split(':') for item in record.split(',')))
    mydictlist.append(mydict)

Example result looks like:
mydictlist[2] = {'id': '2', 'device_data': '123', 'created_at': '2020-04-03'}


text:
Q: Hyperlink in MS Word to an anchor on a web page I need to insert the following link in an MS Word document:

https://creabook.app/guide/topic.htm?#t=Part_1_Preliminaries%2FChapter%201%2C3%20Book%20cover%2FChapter_1%2C3_Book_cover.htm#subtitle

This redirects to the #subtitle anchor of the Web page.
When I save the link in the MS Word document, the format does not take into account the anchor
I use MS Word 2019
Anyone have an idea how to insert links containing anchors?
Thx !
I tried to deactivate "update links on save" in File > Option > Advanced Options > General > Web Options > Files
No result.


text:
Q: Special functions and LambertW Consider equation $\exp(-x) = x$.
Solution is so-called $\text{LambertW}(1)$.
It is beautiful special function called LambertW function or polylog.
Now consider $\cos(x) = x$ and $\sin(x) = x$.
What beautiful special functions solve above equations?


text:
Q: Hide / Change WooCommerce admin notice Hi WooCommerce ninjas!
I'm developing WooCommerce plugin and every time when I submit form (Save Changes button) on top shows update notice with 'Your settings have been saved.'. How I can hide or change this notice, I'm use woocommerce_show_admin_notice filter but don't work in my plugin class. Below is part of code from my plugin. Any ideas for hook who will be usefull?
Great thanks!
<?php
class name_of_plugin extends WC_Payment_Gateway {
   public $error = '';

   // Setup our Gateway's id, description and other values
   function __construct() {
    $this->id = "name_of_plugin";
    $this->method_title = __( "Name", 'domain' );
    $this->method_description = __( "Gateway Plug-in for WooCommerce", 'domain' );
    $this->title = __( "TFS VPOS", 'domain' );
    $this->icon = null;
    $this->has_fields = false;
    $this->init_settings();
    $this->init_form_fields();
    $this->title = $this->get_option( 'title' );

    $this->testurl = 'https://example.com/payment/api';
    $this->liveurl = 'https://example.com/payment/api';

    // Save settings
    if ( is_admin()) {
        add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
    }

    // Disable Admin Notice
    add_filter( 'woocommerce_show_admin_notice', array( $this, 'shapeSpace_custom_admin_notice' ), 10, 2 );
    // add the filter
    add_filter( 'woocommerce_add_error', array( $this, 'filter_woocommerce_add_notice_type' ), 10, 1 );

   } // End __construct()

  // display custom admin notice
  public function filter_woocommerce_add_notice_type($true, $notice ) {
    // magic happen here...
    return $true;
  }

A: I can't see any proper hook that can be used to remove this.
But these 2 seems to work.
My first thought is to reload the page so the settings text will be gone at the time. Something like this.
add_action( 'woocommerce_sections_checkout', 'woocommerce_sections_checkout' );
function woocommerce_sections_checkout() {

    if ( isset( $_GET['section'] ) && isset( $_REQUEST['_wpnonce'] ) && ( $_GET['section'] === 'paypal' )
        && wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-settings' ) ) {

        WC_Admin_Settings::add_message( __( 'Your settings have been saved!', 'woocommerce' ) );
        wp_safe_redirect( wp_get_raw_referer() );
        exit();
    }
}

Then my second option is if you wanted to change the text, we can use the filter gettext.
add_filter( 'gettext', 'woocommerce_save_settings_text', 20, 3 );
function woocommerce_save_settings_text( $translated_text, $text, $domain ) {

    if ( ( $domain == 'woocommerce' ) && isset( $_GET['section'] ) && ( $_GET['section'] === 'paypal' ) ) {
        switch ( $translated_text ) {
            case 'Your settings have been saved.' :
                $translated_text = __( 'Your awesome settings have been saved.', 'woocommerce' );
                break;
        }
    }
    return $translated_text;
}

Please do note that this code is just an example and will work for paypal settings. Change everything that is needed.


text:
Q: Is there a dynamic way of displaying elements in HTML? I have an array $phrases where each cell either stores a phrase which is to be displayed to the user or else a "***" which signifies that an input element is to be placed at that position. I have attached an image to make myself clearer.
$phrases[0] = "Lorem ipsum dolor";
$phrases[1] = "***";
$phrases[2] = "consectetur adipiscing elit";
$phrases[3] = "***";
$phrases[4] = "***";
$phrases[5] = "quis nostrud exercitation";

My question is: how can I make my code adapt to any given array?

A:

var $phrases = [], htmlString = "";
$phrases[0] = "Lorem ipsum dolor";
$phrases[1] = "***";
$phrases[2] = "consectetur adipiscing elit";
$phrases[3] = "***";
$phrases[4] = "***";
$phrases[5] = "quis nostrud exercitation";

for (var i = 0; i < $phrases.length; i++) { //loop through $phrases
  if ($phrases[i] == "***")
    htmlString += "<input type='text'>" //needs input
  else
    htmlString += "" + $phrases[i] + ""; //known value
}

document.getElementById('container').innerHTML = htmlString; //place our htmlString on the page


text:
Q: How to be sure that Newtons method converge to find the optimal solution for a strictly convex one-variable function? I have a function of one variable with a positive domain $(0, \infty)$. This function is strictly convex with any parameters (the second derivative is positive). I want to minimize this function.
In the examples that I have tried, I always found the optimal solution with Newton's method (with a tolerance level being not a problem). However, how can I guarantee that I will always find the optimal solution using this method for this function with different parameters? I have been looking for that answer in some books (e.g. Nonlinear Programming, Mordecai Avriel) but didn't find a clear answer. It seems that strict convexity is a necessary condition. But is it sufficient?
I would appreciate an answer with the corresponding book to dive deeper. Moreover, a numerical example would also be appreciated if possible.
Thanks.
Edit 1: As additional information, the function $f(x)$ tends to $\infty$ when $x$ approaches both $0$ and $\infty$.

A: It is not sufficient, since the first (for example) Newton step could take you to the negative numbers, so outside your domain. You may have more subtle problems too, see the wikipedia article.


text:
Q: Почему не срабатывает header location? Код регистрации пользователей. После нажатия на кнопку , редирект не происходит
 <?php
 if (isset($_POST['reg'])) {
  $login = htmlspecialchars($_POST['login']);
  $password = htmlspecialchars($_POST ['password']);
  $email = htmlspecialchars($_POST ['email']);
  $bad = false;
  session_start();
  unset($_SESSION['error_login']);
  unset($_SESSION['error_password']);
  unset($_SESSION['reg_success']);
  if ((strlen($login) < 3) || (strlen($login) > 32)) {
  $_SESSION['error_login'] = 1;
  $bad = true;
  }
  if ((strlen($password) < 6) || (strlen($password) > 32)) {
  $_SESSION['error_password'] = 1;
  $bad = true;
  }
  if (!$bad) {
  $mysqli = new mysqli("localhost", "root", "", "Hunter");
  $password = md5($password);
  $mysqli->query("INSERT INTO users ('login', 'password', 'email') VALUES
  ('$login', '$password', '$email')");
  $mysqli->close();
  $_SESSION['reg_success'] = 1;
  header("Location: index.php");
  }
  }
  ?>

A: Может заголовки отправлены до того как вы пытайтесь сделать Redirect ?
Найдите в файле php.ini строку поставьте на on (по умолчанию поставлен off).Так вы можете узнать проблему.
Или просто вместо редиректа с помощью пхп используйте js:
echo '<script>
    location.href = "/index.php";
</script>'


text:
Q: Some undesired words appeared in Google's snippets, how to get read of it? I know Google's creation of sites' titles and descriptions (or "snippets") are mainly come from META description. However, when one of my web pages shows up, there are some undesired words like price (which is not good at all). What I want it to show is just the description of the product rather than its price. Actually the price only mentioned twice in the whole page.
How could this happen? And how can I remedy it?

A: Including the price in the snippet is actually very desirable for most people. If your price is higher than the competition's for the same products they probably don't want to buy from you and check out other results instead.
To make sure the search engines don't see the price (and thus don't display it in the results) you should use JavaScript. I think even Amazon does this to prevent screen scraping in some cases. It should be easy, especially with something like jQuery.
$('#priceForProduct987A').html("$125")

A: You should be able to control the snippet displayed by google through the use of the meta tags:
http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=79812
However the results displayed by Google in this case might be different if someone is trying to do some searching on a product. Google will then think you're shopping for that product and try to display the price of it. This might be the case for you.


text:
Q: Can I give a class to a path drawn on a canvas with javascript? I'm randomly drawing little stars on a canvas with the beginPath() method like this:
function makeStars(){
  for(let i=0; i<100; i++){
    let startingX = Math.floor(Math.random()*canvasWidth);
    let startingY = Math.floor(Math.random()*canvasHeight);
    ctx.beginPath();
    ctx.moveTo(startingX, startingY);
    ctx.lineTo(startingX-3,startingY+9.4);
    ctx.lineTo(startingX+4.5, startingY+3.5);
    ctx.lineTo(startingX-4.5, startingY+3.4);
    ctx.lineTo(startingX+3, startingY+9.4);
    ctx.closePath();
    ctx.fill();
  }

Is it possible to give each path a class? Something like ctx.classList.add('star');? Ultimately, I was hoping to be able to animate them with CSS.
Thanks!
Edit
Looks like CSS is not the way to go. I think I'll just try to animate my stars with javaScript in a setInterval loop. Here's a codepen of what I'm working with. Twinkling Stars Canvas

A: The short answer is: No. CSS doesn't act on elements drawn on a canvas.
Drawing to a canvas is like drawing directly to paper. You're using the 2D context to act on the pen. While you could figure out a way to read the CSS and perform the animations (by redrawing and redrawing the canvas), I would think that would be way more difficult than any other alternative.
If you're set on using CSS, one alternative is to use SVG+CSS. The elements within the SVG can react to your CSS, much like HTML elements.
If you absolutely have to use a canvas, you could also draw the SVG to your canvas. Convert the SVG to a Data URI, then load that URI into an Image object, which you can then putImage onto the canvas. You would have to figure out how to draw each time the SVG updates, or poll for the new SVG information at an interval (like requestAnimationFrame).

A: No, CSS cannot animate or interact with canvas drawing.
But You can create a Star class which will provide OOP way of updating, rendering and animating the stars.
and then push all of the stars in an array and update/render them on animate loop.
https://codepen.io/anuraghazra/pen/WLLQJv


text:
Q: Checkbox issue in ListView Scrolling I have listview with text and checkbox. The checkbox are behaving weirdly while scrolling the list view. It seems to be a recycling issue. Anyways I tried various options suggested in some similar posts but none of them working for me. I tried set and get tag position as suggested in one of the posts but hard luck. I am using custom adapter in my activity file for the list view. Below are some code snippets;
 Activity class:
lv = (ListView) findViewById(R.id.itemdisplay_listview);
lv.setAdapter(new CustomAdapter(this, itemNames, tableNo));

Custom Adapter:
private class CustomAdapter extends BaseAdapter {

        private List<String> mListItems;
        private LayoutInflater mLayoutInflater;
        ViewHolder holder;
        int a = 1;

        public CustomAdapter(Context context, List<String> arrayList,
                String table) {
            tableNumber = table;
            mListItems = arrayList;

            // get the layout inflater
            mLayoutInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mListItems.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        private class ViewHolder {

            TextView itemName, quantity;
            CheckBox checkbox;
            ImageButton addBtn, minusBtn;

        }

        @Override
        public View getView(int position, View convertview, ViewGroup viewGroup) {

            // create a ViewHolder reference

            // check to see if the reused view is null or not, if is not null
            // then
            // reuse it
            if (convertview == null) {
                holder = new ViewHolder();

                convertview = mLayoutInflater.inflate(
                        R.layout.itemdisplay_list, null);

                holder.itemName = (TextView) convertview
                        .findViewById(R.id.itemdisplaylist_name);
                holder.addBtn = (ImageButton) convertview
                        .findViewById(R.id.itemdisplaylist_add);
                holder.minusBtn = (ImageButton) convertview
                        .findViewById(R.id.itemdisplaylist_minus);
                holder.quantity = (TextView) convertview
                        .findViewById(R.id.itemdisplaylist_quantity);
                holder.checkbox = (CheckBox) convertview
                        .findViewById(R.id.itemdisplaylist_cbox);

                // holder.checkbox.setTag(position);

                // the setTag is used to store the data within this view
                convertview.setTag(holder);
            } else {
                // the getTag returns the viewHolder object set as a tag to the
                // view
                holder = (ViewHolder) convertview.getTag();
            }

            holder.checkbox.setOnClickListener(checkListener);
            doneBtn.setEnabled(true);

            holder.minusBtn.setImageResource(R.drawable.minus);
            holder.quantity.setText(String.valueOf(a));
            holder.addBtn.setImageResource(R.drawable.add);
            holder.addBtn.setOnClickListener(addBtnClick);
            holder.minusBtn.setOnClickListener(minusBtnClick);

            String stringItem = mListItems.get(position);

            if (stringItem != null) {
                if (holder.itemName != null) {
                    // set the item name on the TextView
                    holder.itemName.setText(stringItem);
                }
            }

            // this method must return the view corresponding to the data at the
            // specified position.
            return convertview;

        }

        private OnClickListener checkListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                /*doneBtn.setOnClickListener(doneBtnClick);*/
                View view = (View) v.getParent();

                CheckBox cb = (CheckBox) view
                        .findViewById(R.id.itemdisplaylist_cbox);
                TextView tv = (TextView) view
                        .findViewById(R.id.itemdisplaylist_name);
                TextView tv1 = (TextView) view
                        .findViewById(R.id.itemdisplaylist_quantity);
                if (cb.isChecked()) {
                    map.put(tv.getText().toString(), tv1.getText().toString());
                } else {
                    for (Iterator<Map.Entry<String, String>> it = map
                            .entrySet().iterator(); it.hasNext();) {

                        Map.Entry<String, String> entry = it.next();
                        String item = entry.getKey();
                        if ((tv.getText().toString()).equals(item)) {
                            it.remove();
                        }
                    }
                }

            }
        };

I have been struggling for quite a long time. Please advise. Thanks.

A: If you have say data for 100  CBs, then you also need to store their checked/unchecked state. lets say a boolean array of 100 elements CheckedStatus[100]. in GetView do
 if(CheckedStatus[position] == true) {
 // check the check box
 } else {
 // uncheck it
}.

The position is the one received in the GetView function

A: in the custom listview adapter call setChecked after calling setOnCheckedChangeListener.This way you sever the link to the old listener from the recycled view.

A: Add a boolean checked variable to ViewHolder. Change it in checkListener. Then in getView add holder.checkbox.setChecked(holder.checked).
Hope it helps.

A: You're going to need to have some sort of model object which retains the state of your checkbox, then use that model instead of a simple String as your datastructure:
// Oversimplified, but adiquate for our purposes.
public class ItemModel
{
    public String text;
    public boolean isChecked;
}

Then, instead of passing an array of Strings to the adapter, pass an array of ItemModels.
The string you'll need will be the text parameter, and then you must set the checkbox value to the isChecked value.
All that's left is changing the isChecked value once the state of the checkbox changes.
Do this inside the getItem method, inside the if(convertView == null) block, after you've initialized the holder.checkbox parameter. Also, make sure to make the position variable in the method parameters final.
Here's the code:
holder.checkbox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                mListItems.get(position).isChecked = isChecked;

            }
        });

Hope this helps :)

A: My guess is you are getting bitten by the recycle issue.I suggest that you remove the listener first using the following in the else statement
holder.checkbox.setOnCheckedChangeListener(null);

In your code as follows:
} else {
                // the getTag returns the viewHolder object set as a tag to the
                // view
                holder = (ViewHolder) convertview.getTag();
                holder.checkbox.setOnCheckedChangeListener(null);
            }


text:
Q: Rails ActiveRecord - query by great-grandchild's attribute How do I find Parent via their GreatGrandChild's attribute for the following setup:
Parent has_many :children
Child belongs_to :parent, has_many :grand_children
GrandChild belongs_to :child, has_many :great_grand_children
GreatGrandChild belongs_to :grand_child

Parent.where(
  children: {
    grand_children: {
      great_grand_children: {:name => "foo"}
    }
  }
)

And how do I when do I use join or preload or eager_load or includes, and what happens if Child/GrandChild/GreatGrandChild is a polymorphic model?

A: First you need to join your required tables telling rails which path to take.
Parent.joins(children: { grand_children: :great_grand_children })

This can be simplified if you add this information into your models.
Parent.has_many :grand_children, through: :children
Parent.has_many :great_grand_children, through: :grand_children

After that a single join is enough, but in the background it will do the same thing
Parent.joins(:great_grand_children)

Now that all the tables are being joined, we can add the where condition. Join already knows where the tables come from, so no need to specify it again.
Parent.joins(:great_grand_children).where(great_grand_children: { name: 'foo' })

Replace joins with includes or similar as needed.
Polymorphism will probably make the situation more complicated, but it's hard to say how from the little information you've provided.


text:
Q: Question about state and domain objects Suppose I create a domain object called UserAdministration, if i have a method called CreateUser how would i pass state to this method, would I create properties on the UserAdministration object and have a CreateUser method or would i pass all the info for CreateUser method in a poco?
Also how do I identify my domain objects?

A:
How would i pass state to this method

There are several ways, here are 3 of them:
1-Pass the values as parameters to public constuctor
2-Pass the values to a public method
3-Create public properties in the class, create an instance, then set each property and call the method without passing parameters

How do I identify my domain objects?

A domain object represents a persistent data store in your solution. If you application is about CRM, then you are bound to deal with domain objects such as parties (customers, companies, etc.), ContactAddress, TouchPoint, etc. All such objects should appear in your UML Class Diagram. A detailed discussion of this could be found in UML, OOA and Domain Driven Design books.


text:
Q: Mesos Future discarded I am trying to run a spark job via Mesos
it throws an exception

WARN MesosExternalShuffleClient: Unable to register app
  6c1b7274-960f-47ef-9fa7-1dd06b05d4f1-0010

with external shuffle service.
Please manually remove shuffle data after driver exit

Error:java.lang.RuntimeException:
  java.lang.UnsupportedOperationException: Unexpected message:
  org.apache.spark.network.shuffle.protocol.mesos.RegisterDriver@88d86a24
  "

and the logs in Stderr as

ERROR CoarseGrainedExecutorBackend: RECEIVED SIGNAL TERM
      INFO DiskBlockManager: Shutdown hook called
      E0911 05:32:34.711486  6619 process.cpp:951] Failed to accept socket: future discarded**

In Spark-Defaults.conf
spark.mesos.coarse          true
spark.network.timeout           3600s
spark.shuffle.io.connectionTimeout  3600s

Who is killing my application..?


text:
Q: Is there a place that I could look at the .NET Stopwatch code and see what it's doing? Is there a place that I could look at the .NET Stopwatch code and see what it's doing?  I'm trying to match up some C++ code to normalize timestamp that .NET stopwatch provides with QueryPerformance call in C++.  (I need to have really good precision if possible, so I need to understand what's actually going on in the .NET Stopwatch calls).
Is the code visible / open somewhere that I can read it online.  Is decompiling mscorlib an option? I'm kind of keeping this as a last resort.

A: Here's what .NET 3.5 does
http://reflector.webtropy.com/default.aspx/Dotnetfx_Win7_3@5@1/Dotnetfx_Win7_3@5@1/3@5@1/DEVDIV/depot/DevDiv/releases/whidbey/NetFXspW7/ndp/fx/src/Services/Monitoring/system/Diagnosticts/Stopwatch@cs/1/Stopwatch@cs
The date on the source code is late 2002, so probably most versions of .NET use the same code.


text:
Q: Is that a good idea to create a groupon like website using Angularjs? I'm new to Angularjs. Now I'm going to create a groupon like website. So I checked lots of similar websites. None of them using the one-page style. So I'm thinking when to use Angularjs. Is that a good idea to create a groupon like website using Angularjs?

A: Heck yea it is. The only thing is to keep the initial page load fast. So you might need to dynamically import your js files using something like: http://requirejs.org/


text:
Q: Exclude certain paths from being autoimported with Lerna, Typescript, and VS Code I have a lerna@3.16 project with a chain of multiple packages.
|-tsconfig.lib.json
|-packages
  |--format
  |----tsconfig.lib.json
  |--helper
  |----tsconfig.lib.json

Each package extends the tsconfig.lib.json from the top level. helper depends on format. When I go to auto import from format, I get three levels of imports:

*

*packages/helper

*@org-name/helper (the right one)

*packages/helper/dist
How do I exclude the two import paths with packages without breaking all imports?

A: Years later, I think that https://www.typescriptlang.org/docs/handbook/project-references.html are the way to handle this with Typescript, at least.
Each tsconfig within packages would have a
   // packages/helper/tsconfig.lib.json
   "references": [
        { "path": "../format" }
    ]

The root package.json would include
"paths": {
   "@org-name/helper": "./packages/helper"
}


text:
Q: Hiding of  after screen size reduction I used 2
 tags to add extra space between 2
 tags while developing the desktop view, but now I'm at the mobile view stage and I need to remove at least 1 of the
 tags. How do I do that?
This is the code.

Name: Frank Boter

Occupation: Publisher, FBoter books

Complaint:

The guys at goatmedia really know their stuff,

A: You could set br {display: none} in css, but I'd recommend you use margin or padding instead of
 in the first place, and then adjust them accordingly for various screen sizes.

p {
  margin: 0;
}

.info {
  /* larger margin on larger screens */
  margin-bottom: 2rem;
}

@media (max-width: 400px) {
  .info {
    /* smaller margin on smaller screens */
    margin-bottom: 0.5rem;
  }
}

Name: Frank Boter

Occupation: Publisher, FBoter books

Complaint:

The guys at goatmedia really know their stuff,

/* you could but shouldn't do this */
br + br {
  display: none; /* hide any br that immediately follows a br */
}

A: You can use a media query to hide one
 tag for certain screen widths. You can adjust the maximum width to meet your needs and multiple queries may be needed to better suit different screen sizes.
@media only screen and (max-width: 600px){
   br + br {
     display: none;
   }
}

However, it is better to use margins instead to more flexibly control the layout spacing and use media queries to reduce the margin on smaller screens.

Name: Frank Boter

Occupation: Publisher, FBoter books

Complaint:

The guys at goatmedia really know their stuff,

.push-top {
   margin-top: 1rem;
}
@media only screen and (max-width: 600px){
   .push-top {
      margin-top: 0.5rem;
   }
}

Name: Frank Boter

Occupation: Publisher, FBoter books

Complaint:

The guys at goatmedia really know their stuff,


text:
Q: How to distribute a module with both a pure Python and Cython version I have a pure Python module and I want to rewrite some of submodules using Cython. Then I would like to add the new Cython submodules to the original Python module and make them available only as an option, meaning that cythoning the module is not compulsory (in which case the 'old' pure Python module should be used).
Here is an example:
my_module
    - __init__.py
    - a.py
    - b.py
    - setup.py

where a.py contains import b.
I want to write b.py in Cython. The idea would be to add a folder containing the .pyx file, for example:
my_module
    - __init_.py
    - a.py
    - b.py
    - setup.py
    cython
        -b.pyx

setup.py would contain the direction to compile b.pyx and to install the module. However, I would like that if someone runs python setup.py install then the pure Python code is installed, whereas if an option is added then the Cython code is compiled and installed.
Any idea how to do that?
Also, how should the file a.py be modified in order to import the correct module?

A: I am not sure about your setup.py requirement (I don't know why you would need that) but as for the runtime import issue, I wrote a decorator to do just that:
from __future__ import print_function
from importlib import import_module
from functools import wraps
import inspect
import sys

MAKE_NOISE = False

def external(f):
    """ Decorator that looks for an external version of
        the decorated function -- if one is found and
        imported, it replaces the decorated function
        in-place (and thus transparently, to would-be
        users of the code). """
    f.__external__ = 0 # Mark func as non-native

    function_name = hasattr(f, 'func_name') and f.func_name or f.__name__
    module_name = inspect.getmodule(f).__name__

    # Always return the straight decoratee func,
    # whenever something goes awry.
    if not function_name or not module_name:
        MAKE_NOISE and print("Bad function or module name (respectively, %s and %s)" % (
            function_name, module_name), file=sys.stderr)
        return f

    # This function is `pylire.process.external()`.
    # It is used to decorate functions in `pylire.process.*`,
    # each of which possibly has a native (Cython) accelerated
    # version waiting to be imported in `pylire.process.ext.*`
    # … for example: if in `pylire/process/my_module.py` you did this:
    #
    #   @external
    #   def my_function(*args, **kwargs):
    #       """ The slow, pure-Python implementation """
    #       pass
    #
    # … and you had a Cython version of `my_function()` set up
    # in `pylire/process/ext/my_module.pyx` – you would get the fast
    # function version, automatically at runtime, without changing code.
    #
    # TL,DR: you'll want to change the `pylire.process.ext` string (below)
    # to match whatever your packages' structure looks like.
    module_file_name = module_name.split('.')[-1]
    module_name = "pylire.process.ext.%s" % module_file_name

    # Import the 'ext' version of process
    try:
        module = import_module(module_name)
    except ImportError:
        MAKE_NOISE and print("Error importing module (%s)" % (
            module_name,), file=sys.stderr)
        return f
    MAKE_NOISE and print("Using ext module: %s" % (
        module_name,), file=sys.stderr)

    # Get the external function with a name that
    # matches that of the decoratee.
    try:
        ext_function = getattr(module, function_name)
    except AttributeError:
        # no matching function in the ext module
        MAKE_NOISE and print("Ext function not found with name (%s)" % (
            function_name,), file=sys.stderr)
        return f
    except TypeError:
        # function_name was probably shit
        MAKE_NOISE and print("Bad name given for ext_function lookup (%s)" % (
            function_name,), file=sys.stderr)
        return f

    # Try to set telltale/convenience attributes
    # on the new external function -- this doesn't
    # always work, for more heavily encythoned
    # and cdef'd function examples.
    try:
        setattr(ext_function, '__external__', 1)
        setattr(ext_function, 'orig', f)
    except AttributeError:
        MAKE_NOISE and print("Bailing, failed setting ext_function attributes (%s)" % (
            function_name,), file=sys.stderr)
        return ext_function
    return wraps(f)(ext_function)

… this lets you decorate functions as @external – and they are replaced at runtime automatically with the Cython-optimized versions you've provided.
If you wanted to extend this idea to replacing entire Cythonized classes, it'd be straightforward to use the same logic in the __new__ method of a metaclass (e.g. opportunistic find-and-replace in the optimized module).

A: My solution was to set up the module like this:
my_module
    - __init_.py
    - a.py
    - b.py
    - setup.py
    cython_my_module
        - __init_.py
        - b.pyx

The setup.py would contain something similar to this:
from distutils.core import setup
from Cython.Build import cythonize

import numpy

setup(
    name='My_module',
    ext_modules=cythonize(["cython_my_module/b.pyx",]),
    include_dirs=[numpy.get_include()],
)

and the file a.py would contain the following lines in the header:
try:
    import cython_my_module.b
except ImportError:
    import b

The way it works is very simple: if you don't do anything (i.e. if you don't compile the cython files) then module a.py imports module b.py; however, if you run python setup.py build_ext --inplace then the compiled cython files will appear inside cython_my_module and the next time you run a.py it will automatically import the cython module b.pyx (actually it will import the compiled library b.so).
So far it seems to work and requires almost no effort. Hope it helps.
fish2000 solution seems more generic but I haven't tried it yet.


text:
Q: I get this error when trying to run an app via flutter on vscode I just finished setting flutter up in VS Code, I created an android emulator and it runs fine, but when i try to launch the demo app of flutter i get this error:
Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Parameter format not correct -

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Kotlin could not find the required JDK tools in the Java installation 'C:\Program Files\Java\jre1.8.0_291' used by Gradle. Make sure Gradle is running on a JDK, not JRE.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org

BUILD FAILED in 4s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

What's the problem?

A: Install Android Studio, it is a must if you are new, you can always use VSCODE for development but Android studio needs to be there.
Best way is uninstall vscode, install android studio, install flutter and dart plugin in android studio, then install vscode, it will work.
Also try running
flutter doctor
What does it say?


text:
Q: Azure worker role stops after fault bucket event daily Worker role instance stops daily and i get following error in WADWindowsEventLogsTable.
Instance status is unhealthy after this event is logged.
Fault bucket , type 0
Event Name: PDUWICA
Response: Not available
Cab Id: 0
Problem signature:
P1: 8
P2: 1.6
P3: 6.3.0.0
P4: 1033
P5: 61
P6:
P7:
P8:
P9:
P10:
Attached files:
These files may be available here:
Analysis symbol:
Rechecking for solution: 0
Report Id: a32d8f81-b668-11e5-80c8-000d3a316974
Report Status: 0
Hashed bucket:

A: Can you enable Intellitrace, re-deploy your instance (suggest to use local emulator if possible for a staging instance), get a more specific information about any unhealthy experience as posted and report the same? Review this link for a step by step guide on how to enable and use Intellitrace (http://justazure.com/microsoft-azure-cloud-services-part-5-debug-monitor-scale/)
Edit:
Once logged in to the instance with Remote assistance.
Try to access the Schedule Tasks, following is the screenshot on my PC and that might get you some specific information.

Once the scheduler runs, try to dig in and look for anything suspicious


text:
Q: Issue with deviantart authentication (PHP) I am trying to connect to deviantart via their oauth2 mechanism. I do get the code to obtain an access token but then I get some strange 404 error when trying to get the access token via file_get_contents. However, when I copy the url I am able to get the access token as desired. Has this sth. do with header settings? This is the code to get the access token:
function getAccessToken($code) {
        $url = "https://www.deviantart.com/oauth2/token";
        $data = array();
        $data["grant_type"] = "authorization_code";
        $data["client_id"] = $this->client_id;
        $data["client_secret"] = $this->client_secret;
        $data["redirect_uri"] = $this->redirect_uri;
        $data["code"] = $code;
        return $this->sendToDeviantArt($url, $data);
}

private function sendToDeviantArt($url=null, $data=array()) {
        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data),
            ),
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
}

A: It took me hours but apparently, deviantart wants to have a USER_AGENT set. So for the records, this works flawlessly (mind the user_agent variable)
    private function sendToDeviantArt($url=null, $data=array()) {
        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data),
                'user_agent' => $_SERVER["HTTP_USER_AGENT"]
            ),
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

EDIT: For the records, we have programmed a wrapper for some deviantart functions and have uploaded a small library on github.

A: This was a pain for me too. Thanks to Jan for the heads up on the user agent. Just thought I'd offer a curl alternative as that's what I was using for this. Obviously edit to your hearts content, but this works if you pass a deviantART api url through it.
function curl($url) {
  // Initiate curl
  $ch = curl_init();
  // Disable SSL verification
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  // Will return the response, if false it print the response
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  // Set the user agent
  curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER["HTTP_USER_AGENT"]);
  // Set the url
  curl_setopt($ch, CURLOPT_URL,$url);
  // Execute
  $result=curl_exec($ch);
  // Closing
  curl_close($ch);
  // Will dump a beauty json :3
  return $result;
}

```
Example usage to get your access token:
$json = json_decode(curl("https://www.deviantart.com/oauth2/token?response_type=code&client_id=0&client_secret=0&grant_type=client_credentials"), true);
$json["access_token"];


text:
Q: Error importing csv dates into a mysql server The following code doesn't work on the part of importing dates and i cant figure why. Dates in the csv are like DD/MM/YYYY and the error is it imports all the data but leaves null every date. Also error says:
ER_UNKNOWN_SYSTEM_VARIABLE: Unknown system variable 'FECHA_POSICION'
Lines in the csv file look like:
EDC00001,66600/7089855,21/01/2021,21/01/2021,"DEPOSIT Deposit",4000,4000
EDC00002,66600/7089855,29/01/2021,29/01/2021,CFDs,"-9,94","3990,06"
USE DATA_BASE;
CREATE TABLE ESTADO_DE_CUENTA (
ID_OPERACION VARCHAR(20) NOT NULL PRIMARY KEY,
ID_CUENTA VARCHAR(20),
FECHA_POSICION DATE,
FECHA_VALOR DATE,
CONCEPTO VARCHAR(100),
IMPORTE FLOAT(12, 2),
SALDO_EN_EFECTIVO FLOAT(12, 2)
);

LOAD DATA LOCAL INFILE 'PATH.csv' INTO TABLE ESTADO_DE_CUENTA2
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(ID_OPERACION, ID_CUENTA, @FECHA_POSICION, @FECHA_VALOR, CONCEPTO, IMPORTE,
SALDO_EN_EFECTIVO)
SET FECHA_POSICION = STR_TO_DATE(@FECHA_POSICION, '%d/%m/%Y')
SET FECHA_VALOR = STR_TO_DATE(@FECHA_VALOR, '%d/%m/%Y')

A: You can call SEt only once and all columsn have to be separated by comma
Like
USE DATA_BASE;
LOAD DATA LOCAL INFILE 'PATH.csv' INTO TABLE ESTADO_DE_CUENTA2
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(ID_OPERACION, ID_CUENTA, @FECHA_POSICION, @FECHA_VALOR, CONCEPTO, IMPORTE,
SALDO_EN_EFECTIVO)
SET `FECHA_POSICION` = STR_TO_DATE(@FECHA_POSICION, '%d/%m/%Y') , `FECHA_VALOR` = STR_TO_DATE(@FECHA_VALOR, '%d/%m/%Y')


text:
Q: Gaussian blur filter causes text above the affected image it to hide I encountered a problem while trying to blur an image in CSS on my webpage: any element rendered above the affected image will hide during and after the procedure. How can I resolve the issue?
For more information about the problem itself, I posted a snippet containing an example featuring that exact problem.

.placeholder {
  display: block;
  /* Align the content within the container near the center. */
  text-align: center;
  /* Calculate both the width and height of the element. */
  width: calc(100vw / 3);
  height: calc(100vw / 3 * 2 / 3);
}

.placeholder img {
  display: inline;
  /* Fill the entire parent element. */
  width: 100%;
  height: 100%;
  /* Adjust the way the image is fit into the parent. */
  object-fit: cover;
  /* Add a transition to the element whenever an effect will be applied to it. */
  transition: all 0.5s linear;
}

.placeholder > p.article {
  display: inline-block;
  /* Calculate the desired margin of the element. */
  margin: calc(-100vw / 3 * 2 / 3 - 1em) auto 0;
  /* Align the element vertically near the middle. */
  vertical-align: middle;
  /* Adjust the readability of the text. */
  color: white;
}

.placeholder:hover img {
  /* Blur the image inside the container when the cursor is above it. */
  filter: blur(4px);
}

A lazy fennec.

Copyright © http://fennek.mobi/

A: Add position: relative to .imageLabel.

body {
  margin: 0;
}
.imageFolder {
  float: left;
  display: block;
  width: calc(100vw / 3 - 0px);
  height: calc(100vw / 3 * 2 / 3 - 0px);
  border: 0px solid #444;
  overflow: hidden;
  text-align: center;
  vertical-align: middle;
}
.imageBox {
  display: inline;
  margin: 0 auto;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.imageBox img {
  display: inline;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.2s ease-in;
}
.imageLabel {
  position: relative;
  display: inline-block;
  margin: calc(0px - 100vw / 3 * 2 / 3) auto 0;
  height: 40px;
  line-height: 40px;
  font-weight: 700;
  font-size: 24px;
  padding: 10px 40px;
  text-decoration: none;
  color: white;
  opacity: 0;
  text-align: center;
  vertical-align: middle;
  border: 1px solid white;
}
.imageFolder:hover > .imageBox img {
  width: calc(100% + 30px);
  height: calc(100% + 20px);
  margin: -10px -15px;
  transition: all 0.6s ease-out;
  filter: blur(4px);
}
.imageFolder:hover > .imageLabel {
  opacity: 1;
  transition: all 0.6s ease-out;
}

Charlotte


text:
Q: Upload a file attachment for Salesforce in C# I've seen this example to build and send an attachment to Salesforce in Java, but how is this accomplished in C#?
Edit - I'm also using this page as a reference, but I still don't know how to finish the last part where I try to create and save the attachment.
SoapClient client = new SoapClient();
LoginResult lr = client.login(new LoginScopeHeader(), username, password);

FileInfo fileInfo = new FileInfo(myFileLocation);
FileStream stream = File.OpenRead(myFileLocation);
byte[] byteArray = new byte[fileInfo.Length];
stream.Read(byteArray, 0, byteArray.Length);

Attachment attachment = new Attachment();
attachment.Body = byteArray;
attachment.Name = myFileName + ".txt";
attachment.IsPrivate = false;

SaveResult saveResult = client.create(new sObject[] { attachment })[0];

A: It looks correct in general. With the following changes.
After calling login, you will need to assign the resulting SessionId and ServerUrl to the client.
SoapClient client = new SoapClient();
LoginResult lr = client.login(new LoginScopeHeader(), username, password);
client.SessionHeaderValue = new SforceService.SessionHeader();
client.SessionHeaderValue.sessionId = li.sessionId;
client.Url = loginResult.serverUrl;

You should check the SaveResult to see if the record was created and what the new Id is.
//...
SaveResult saveResult = client.create(new sObject[] { attachment })[0];
if (saveResult .success){
    // saveResult.id contains id of newly created attachment
} else {
    //saveResult .errors[0] contains reason why attachment couldn't be created.
}


text:
Q: Does iOS 8.3 now support Wifi debugging? I updated iOS on my phone to 8.3 and I saw this message popup on first boot, but I have not seen it since:

I have been searching all day for information and I can't find a single reference to this message or to Xcode supporting wifi debug.
I am using a macbook pro 2009 model, and I have read that this is not compatible with the new continuity features (as well as airdrop etc). I am wondering if this is part of the wifi debug (and also if BTLE is involved at all). Of course it is all speculation since I cannot find any documentation about this.
Has anybody used wifi debug, or can point me to any documentation?

A: No, the feature was disabled as it causes serious security flows, for example when debugging you can fake location for any app, access confidential data like your number, udid etc. WiFi can be used now only to sync using iTunes.
It's restricted to USB only. You would need to write a bridge between USB and WiFi. You could in theory connect iPhone to Raspberry Pi, use open source crossplatform libMobileDevice. And mirror all USB requests from your XCode to this device USB.


text:
Q: Cannot read property 'keyCode' of undefined when testing for Enter Press I've read several post on here about this issue and still can't seem to fix this error. For context, I am working in a custom PopupWindow class that has a custom text_area box. This shouldn't be relative, except the typical properties for react input boxes are NOT available to be in the situation (i.e. onKeyPress). It has been replaced with onEnterKeyPress but essentially works the same.
Event Handler:
getKeyPress = evt => {
    let pressed = evt.keyCode || evt.which;
    if(document.activeElement.tagName.toLocaleLowerCase() === 'textarea'){
        console.log("TRUE"); //Is returning TRUE
        if(pressed === 13){
            "
"
        }
    }
}

Invoking Event Handler:
<PopupWindow onEnterKeyPress= {this.getKeyPress} >content here... </PopupWindow>

A: Given the limited information you're providing I think that in order to handle custom event you should register them with vanilla js in the component in one of the lifecycle methods. For example:
componentDidMount() {
     window.addEventListener("customEvent", this.getKeyPress);
}

And of course unregister them afterwards.

A: Here's a simple keyPress event that shows keyCode. Theoretically, it should work the same when using custom events. Note that I am using charCode instead of keyCode:

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          keyCode: null
        };
        this.handleKeyPress = this.handleKeyPress.bind(this);
    }

    handleKeyPress = (event) => {
      this.setState({ keyCode: event.charCode })
    }

    render() {

    return (

          <textarea onKeyPress={this.handleKeyPress} />
          {this.state.keyCode && KeyCode = {this.state.keyCode}}

      );
  }
}

ReactDOM.render( < App / > ,
  document.getElementById('root')
);
textarea {
  width: 100%;
  height: 100px;
}


text:
Q: Export HTML to PDF always align at the bottom of a new page I am having a problem with export html to PDF. I would like section at the bottom to be always aligned at the bottom of a new page.
Right now this section (when it comes to page break) is aligned at the top of a new page:

Code for that section:

     BLAGO DOSTAVIL: ______________________

     Podpis

     Datum: ______________________

     BLAGO PREVZEL: ______________________

     Podpis

     Datum: ______________________

     testting d.o.o., testing, ID za DDV: testing, matična št.: testing

     tel: +386 XXXXXXXXXX, fax: +386 1 XXXXXXXXX, e-mail: info@XXXX.si, web: www.xxxxxxx.si

     Družba je vpisana pri okrožnem sodišču v Ljubljani, št. vpisa v registru: 1/XXXXX/00, ustanovni kapital: XX.000 EUR

     Račun odprt pri NLB d.d., Iban: SIXXXXXXX, SWIFT-BIC: LJBASI2X

Here is my code for the whole page (including section at the bottom which jumps into new page at page break):

Vrsta blaga/storitve
                                Interna številka
                                Prodana koda
                                Količina
                                EnM
                                Cena brez DDV
                                Vrednost brez DDV
                                DDV
                                Znesek DDV
                                Vrednost z DDV

Večerja na zajli

VzlSSlNYVlo=

<input type='checkbox'>

1,00
KOM
91,14 €
91,14 €
9,50 %
8,66 €
99,80 €

Veliki kuharski mojster

TDZKVzRDVks=

<input type='checkbox'>

7,00
KOM
65,69 €
459,83 €
22,00 %
101,16 €
560,99 €

Q0U2RURCVks=

<input type='checkbox'>

RFg0TVZXVks=

<input type='checkbox'>

OFdGRTJLVks=

<input type='checkbox'>

QlROR0NMVks=

<input type='checkbox'>

SjNYWkJOVks=

<input type='checkbox'>

M0RFWURXVks=

<input type='checkbox'>

Specifikacija obračunanega davka, dokumenta št.:

Stopnja	Osnova za DDV	Znesek DDV	Vrednost z DDV

9,5 %	91,14 €	8,66 €	99,80 €

22 %	459,83 €	101,16 €	560,99 €

Skupaj brez DDV:	550,97 €

Osnova za DDV	550,97 €

DDV:	109,82 €

SKUPAJ:
660,79 €

     BLAGO DOSTAVIL: ______________________

     Podpis

     Datum: ______________________

     BLAGO PREVZEL: ______________________

     Podpis

     Datum: ______________________

     testting d.o.o., testing, ID za DDV: testing, matična št.: testing

     tel: +386 XXXXXXXXXX, fax: +386 1 XXXXXXXXX, e-mail: info@XXXX.si, web: www.xxxxxxx.si

     Družba je vpisana pri okrožnem sodišču v Ljubljani, št. vpisa v registru: 1/XXXXX/00, ustanovni kapital: XX.000 EUR

     Račun odprt pri NLB d.d., Iban: SIXXXXXXX, SWIFT-BIC: LJBASI2X

A: I just moved the table holding contact info at the bottom of the page as a new:

to the table we are going to stick it to the bottom of the page while printing.
Then you need to only add a style rule for @media print, like this:
@media print{
  table#stickToFooter{
    position: fixed;
    bottom: 0;
  }
}

Say, I didn't manipulate you code in other parts, but just as a best-practice rule, please try to avoid surrounding none-inline level elements in inline tags. I mean it'd be much better if you set table's font-family & size using these styling elements:
table{
  font-family: Verdana, sans-serif;
  font-size: 10px
}

than enclosing it inside a ... tag. Thanks in advance.

Vrsta blaga/storitve
                                Interna številka
                                Prodana koda
                                Količina
                                EnM
                                Cena brez DDV
                                Vrednost brez DDV
                                DDV
                                Znesek DDV
                                Vrednost z DDV

Večerja na zajli

VzlSSlNYVlo=

<input type='checkbox'>

1,00
KOM
91,14 €
91,14 €
9,50 %
8,66 €
99,80 €

Veliki kuharski mojster

TDZKVzRDVks=

<input type='checkbox'>

7,00
KOM
65,69 €
459,83 €
22,00 %
101,16 €
560,99 €

Q0U2RURCVks=

<input type='checkbox'>

RFg0TVZXVks=

<input type='checkbox'>

OFdGRTJLVks=

<input type='checkbox'>

QlROR0NMVks=

<input type='checkbox'>

SjNYWkJOVks=

<input type='checkbox'>

M0RFWURXVks=

<input type='checkbox'>

Specifikacija obračunanega davka, dokumenta št.:

Stopnja	Osnova za DDV	Znesek DDV	Vrednost z DDV

9,5 %	91,14 €	8,66 €	99,80 €

22 %	459,83 €	101,16 €	560,99 €

Skupaj brez DDV:	550,97 €

Osnova za DDV	550,97 €

DDV:	109,82 €

SKUPAJ:
660,79 €

     BLAGO DOSTAVIL: ______________________

     Podpis

     Datum: ______________________

     BLAGO PREVZEL: ______________________

     Podpis

     Datum: ______________________

                        testting d.o.o., testing, ID za DDV: testing, matična št.: testing

                        tel: +386 XXXXXXXXXX, fax: +386 1 XXXXXXXXX, e-mail: info@XXXX.si, web: www.xxxxxxx.si

                        Družba je vpisana pri okrožnem sodišču v Ljubljani, št. vpisa v registru: 1/XXXXX/00, ustanovni kapital: XX.000 EUR

                        Račun odprt pri NLB d.d., Iban: SIXXXXXXX, SWIFT-BIC: LJBASI2X

A: I used JS for solving your problem and make minor changes in your code. You can look at it, I marked my changes with <--EDIT--> comment.
I assumed, that your problem occur when either of your 'Type of goods' table or 'DDV' table get too high to fit on one page with your 'signature' section.
My JS script use function to check height of those tables, make calculation, and if combined height is bigger than certain treshold (825px) it manualy break page. After that, it set margin for your 'signature' section to move it at the bottom of new page (margin wary from 1110px for EDGE&FFOX to 1160 for CHROME).
Note, that this changes will take effect only for "print" version (i used separate <.style> for @media print) and are not visible in web wersion.
I hope you will find it usefull.
CODE:

<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">


text:
Q: Sort images based on comparing a fraction of their pixels in a region with a folder of images and move them into seperate folders this is image 1
this is image 2
now, i want the program to basically take this part of the image (Note - It's important the part will be at the bottom left of an image)
and compare it to the rest of the images, if a match has been found, move the matching files into the same folder, if an image isn't matched it goes to the next one and checks for match, when it finished going through everything, it will go to the first unmatched image and take a part from it, just like image , and do the whole process again, but into a new, seperate folder.
the results should be a folder with multiple folders of all the pictures orginized, where every folder has a similar part in every image in the folder.
I've tried making a macro for it but after 20 tries I gave up, maybe the macro program bottle-necked me but I don't know any other way to do it except coding which im bad at.
( macro - macro )
I only know how to code in python and only beginner stuff so I have no idea how to do it.

A: I would reccomand using skimage.
You can easily compare two images if you load them as an array and then define the pixels that you want to check:
from skimage import io

testimage = io.imread("test.png")
testimage2 = io.imread("test2.png")
sameImg = True

for y in range(1200,1400):
   for x in range(0,200):
       if testimage[y][x][0] != testimage2[y][x][0]:
           sameImg = False

print(sameImg)

Then you can move them with os
os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

put it in a loop and your done


text:
Q: EF-Code First navigation property foreign key in complex type I have complex type for Audit fields
My complex type:
[ComplexType]
public class AuditData  {
    [Column("CreatorUserId")]
    public int? CreatorUserId { get; set; }
    public DateTime? CreationTime { get; set; }
    [Column("ModifierUserId")]
    public int? ModifierUserId { get; set; }
    public DateTime? ModificationTime { get; set; }
}

My base Entity (all other inherti this one) has AuditData property:
public abstract class Entity : IEntity, IAuditedEntity, INotifiedDbContextBeforeSave
{

    // Summary:
    //     Unique identifier for this entity.
    public int Id { get; set; }
    public bool IsActive { get; set; }
    public int Old_Id { get; set; }
    public string Old_TableName { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
    public AuditData AuditData { get; set; }
    // can this 2 lines below work as navigation property with foreign key in complex type
    public virtual User CreatorUser { get; set; }
    public virtual User ModifierUser { get; set; }

    //... other fields
}

I have 2 navigation properties CreatorUser and ModifierUser.
I know you cant have navigation property in ComplexType but can my navigation property on entity be mapped with foreign key in complexType
something like:
    [ForeignKey("CreatorUserId")] // --> should point to AuditData.CreatorUserId
    public virtual User CreatorUser { get; set; }

becouse CreatorUserId will be property in every entity but EF is not aware of it.
Mybe there is solution in fluent API ?

A: The official documentation says:

Complex types are non-scalar properties of entity types that enable scalar properties to be organized within entities. Like entities, complex types consist of scalar properties or other complex type properties. Because complex types do not have keys, complex type objects cannot be managed by the Entity Framework apart from the parent object.

It follows that that complex types can not participate in any relations among entities, so they can't contain foreign keys