text:
Q: Scrapy "The 'Twisted>=13.1.0' distribution was not found and is required by Scrapy" I'm installing scrapy on Ubuntu 12.04, python 3.5.2 inside a virtualenv. I've had so much trouble installing scrapy but I've finally got all the requirements installed. I had to manually install twisted to get the installation to complete, but I have Twisted 17.0 installed. However, when I try to run the tutorial I get the following error:
Traceback (most recent call last):
 File "/usr/local/bin/scrapy", line 5, in <module>
  from pkg_resources import load_entry_point
 File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2927, in <module>
@_call_aside
File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2913, in _call_aside
f(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 2940, in _initialize_master_working_set
working_set = WorkingSet._build_master()
File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 635, in _build_master
ws.require(__requires__)
File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 943, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/local/lib/python3.5/site-packages/pkg_resources/__init__.py", line 829, in resolve
raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'Twisted>=13.1.0' distribution was not found and is required by Scrapy

Twisted 17.0 is installed and seems to be working. When I import scrapy and twisted in python I get no errors (it finds the module), but as a command, scrapy doesn't work.
Python 3.5.2 (default, Nov  2 2016, 11:15:44)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import scrapy
>>> import twisted

A: You will need the build dependencies installed for all of the extension modules involved.  That's going to include at least gcc, libffi-dev, and libssl-dev (but possibly more):
sudo apt-get install gcc libffi-dev libssl-dev

With the build dependencies installed, you should install all of the Python software into the virtualenv.
virtualenv --python=python3.5 scrapy-environment
. scrapy-environment/bin/activate
pip install scrapy
scrapy ...

If you encounter some error with this, you should update your question to include details of that error.


text:
Q: AWS Elastic Beanstalk - Custom Domain Problem with Route 53 hosted zone Hi i have laravel app deployed with AWS Elastic Beanstalk.
I have domain on cloudflare, I created hosted zone in AWS Route 53 with A record which is alias to my Elastic Beanstalk env but if i want to access app with this domain it just doesnt work, if i create A record with EC2 ip associated with Elastic Beanstalk env everything works, but when autoscaling pops up this ip changes, I tried to point DNS with CNAME to .elasticbeanstalk domain associated with app but same result, anyone had similar problem?
I tried using dig mydomain and answer section gives me 2 ip addresses - typing both to browser lets me access application, but neither of those two are same as ec2 intance associated with Elastic Beanstalk env,
I also tried using DNS Checker online, seems like some DNS servers reads my domain as those two IP addresses from dig command, some DNS servers reads my domain as a combination of EC2 instance address + one of address displayed in dig command
Any idea what can cause this? Server works on amazon linux + nginx on which i used certbot to get SSL Certificates (all 80 port requests are pointed to 443 port which seems working - because after typing http://domain I get 301 redirect to https://) nginx -t tells that configuration of nginx is ok

A: The problem was lack of HTTPS listener in load balancer.
To resolve something like this:

*

*Go to configuration

*Find Load Balancer and Edit

*Add Listener for 443 Port HTTPS and SSL certificate

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find & Round the time to nearest half an hour from a single file I have yearly time data for one year in a single file with 30 min interval such as
"01-01-2013 00:00" "01-01-2013 00:30" "01-01-2013 01:00" "01-01-2013 01:30" "01-01-2013 02:00" "01-01-2013 02:30".....

But in the entire data, some of them contains
"08-28-2013 14:53", "08-28-2013 15:37"

I need to find those from the entire record and to replace(round off) into 30 mins time interval like
"08-28-2013 15:00", "08-28-2013 15:30"

Help me in this..

A: datetimes <- c("08-28-2013 14:53", "08-28-2013 15:37")
datetimes <- strptime(datetimes, "%m-%d-%Y %H:%M", tz="GMT")
datetimes$min <- round(datetimes$min / 30) * 30
#1] "2013-08-28 15:00:00 GMT" "2013-08-28 15:30:00 GMT"


text:
Q: How to design a single interface to save different Collections in Delphi? I have multiple collections like:
TFooList = TObjectDictionary<string,TFoo>;
TBarList = TObjectDictionary<string,TBar>;
....

TRoot = class
   value : string
end;

TFoo = class(TRoot)
...
end;

TBar = class(TRoot)
...
end;

And I have an interface/class that could save or load collections:
ISave = interface
  procedure Save( TDictionary<string, string> );
  function Load: TDictionary<string, string>;
end;

Note that the interface expects a key/string pair collection in order to work properly.
I implemented some ISave classes in order to load/save the collection to/from file or databases:
TDbSave = class( TInterfacedObject , ISave )
   ....
end;
iSave := TDbSave( ConnString )

TFileSave = class( TInterfacedObject , ISave )
   ....
end;
iSave := TFileSave( fileName );

So, the last piece would be inherit from each collection and create the save/load methods to "translate" each collection into/from TDictionary(string, string)
    TFooListSavable = TFooList;
      procedure Create( save_load : ISave );
      procedure Save;
      procedure Load;
      ....
   end;

   procedure TFooListSavable.Save
      // 1. create a  TDictionary<string, string>
      // 2. load the dictionary above with my collection translating
      //    each Foo object into a string
      // 3. call save_load.Save( dictionary );
   end;
   procedure TFooListSavable.Load
      // 1. create a  TDictionary<string, string>
      // 2. call save_load.load to load it
      // 3. Move over the collection and translate string into TFoo and
      // 4. AddOrEquals each TFoo created into TFooListSavable.
   end;

So, I have two problems with this approach:
1) The interface that save or load expects a string value from the Collection and, although all the objects in each collection inherit from a class that has this string defined, I don't know how to transform a collection like TDictionary<string,TFoo> into a TDictionary<string,string> without resorting to the code above (which will duplicate the collection in order to pass it to iSave object).
2) I feel that, although I can replace iSave objects changing the way the collections would be saved/loaded without changing the collections themselves, I don't know if it is the best approach to save/load collections that keep related objects.

A: I think you are going about this the wrong way.
ISave should not have any concept of any TDictionary at all.  It should just expose methods for reading/writing basic data types (integers, strings, etc).  Let TFooListSavable and TBarListSavable decide how to serialize their respective TDictionary data however they want, calling the ISave methods as needed.
Even better would be if TFooListSavable and TBarListSavable pass ISave to each individual TFoo/TBar and let them serialize their own data members directly.
For example, something like this:
type
  ISerialize = interface
    function HasData: Boolean;
    procedure StartWriteCollection;
    procedure StartWriteItem;
    procedure FinishWriteCollection;
    procedure FInishWriteItem;
    procedure WriteBoolean(value: Boolean);
    procedure WriteInteger(value: Integer);
    procedure WriteString(const value: String);
    ...
    procedure StartReadCollection;
    procedure StartReadItem;
    procedure FinishReadCollection;
    procedure FinishReadItem;
    function ReadBoolean: Boolean;
    function ReadInteger: Integer;
    function ReadString: String;
    ...
  end;

  TRoot = class
  public
    value : string;
    constructor Create; virtual;
    procedure Save(Dest: ISerialize); virtual;
    procedure Load(Src: ISerialize); virtual;
  end;

  TBaseList<T: TRoot, constructor> = class(TObjectDictionary<string, T>)
  public
    procedure Save(Dest: ISerialize);
    procedure Load(Src: ISerialize);
  end;

  TFoo = class(TRoot)
  public
    myint: Integer;
    ...
    procedure Save(Dest: ISerialize); override;
    procedure Load(Src: ISerialize); override;
  end;
  TFooList = TBaseList<TFoo>;

  TBar = class(TRoot)
    mybool: Boolean;
    ...
    procedure Save(Dest: ISerialize); override;
    procedure Load(Src: ISerialize); override;
  end;
  TBarList = TBaseList<TBar>;

  TDbSerialize = class(TInterfacedObject, ISerialize)
    ...
  end;

  TFileSerialize = class(TInterfacedObject, ISerialize)
    ...
  end;

  procedure TBaseList<T>.Save(Dest: ISerialize);
  var
    pair: TPair<string, T>;
  begin
    Dest.StartWriteCollection;
    for pair in Self do
    begin
      Dest.StartWriteItem;
      Dest.WriteString(pair.Key);
      TRoot(pair.Value).Save(Dest);
      Dest.FinishWriteItem;
    end;
    Dest.FinishWriteCollection;
  end;

  procedure TBaseList<T>.Load(Src: ISerialize);
  var
    Cnt, I: Integer;
    key: string;
    value: T;
  begin
    Self.Clear;
    Src.StartReadCollection;
    While Src.HasData do
    begin
      Src.StartReadItem;
      key := Src.ReadString;
      value := T.Create;
      try
        value.Load(Src);
        Self.Add(key, value);
      except
        value.Free;
        raise;
      end;
      Src.FinishReadItem;
    end;
    Src.FinishReadCollection;
  end;

  procedure TRoot.Save(Dest: ISerialize);
  begin
    Dest.WriteString(value);
  end;

  procedure TRoot.Load(Src: ISerialize);
  begin
    value := Src.ReadString;
  end;

  procedure TFoo.Save(Dest: ISerialize);
  begin
    inherited;
    Dest.WriteInteger(myint);
  end;

  procedure TFoo.Load(Src: ISerialize);
  begin
    inherited;
    myint := Src.ReadInteger;
  end;

  procedure TBar.Save(Dest: ISerialize);
  begin
    inherited;
    Dest.WriteBoolean(mybool);
  end;

  procedure TBar.Load(Src: ISerialize);
  begin
    inherited;
    mybool := Src.ReadBoolean;
  end;


text:
Q: Removing Chromium browser from Debian 9 system I've downloded Chromium version 80 in the form of a zip file. The extracted folder "chrome-linux" contains a
script "chrome-wrapper" which when executed install the browser and put the logo on the desktop. I was able to launch and use the browser as expected. Now I'd like to remove it but don't know how. I couldn't find a script and Synaptic doesn't seem to find it.

A: You can make use of checkinstall.
From man checkinstall:
       checkinstall is a program that monitors  an  installation  procedure  (such  as  make
       install,  install.sh  ),  and  creates a standard package for your distribution (cur‐
       rently deb, rpm and tgz packages are supported) that you  can  install  through  your
       distribution's package management system (dpkg, rpm or installpkg).

Running checkinstall chrome-wrapper will wrap around the installation-script, create a debian-package and install said package.
After that, you can just deinstall the package with dpkg -r or apt remove or whichever package manager you like best.
It is a good habit to ALWAYS use checkinstall with installation-scripts and make install.


text:
Q: how to remove the border of a collapsible div/li in materialize.css I am trying to create a collapsible within a collection list item. But I don't want the greyish border of the collapsible divs to be visible in this collapsible.
the markup:

First

Lorem ipsum dolor sit amet.

the css:
.collapsible-header, .collapsible-body, .collapsible, ul.collapsible>li
{
  margin-left: 0px;
  margin-right: 0px;
  margin-top: 0px;
  margin-bottom: 0px;
  padding: 0rem !important;
  border-top: 0px!important;
  border-right: 0px!important;
  border-left: 0px!important;
  border-bottom: 0px!important;
  box-shadow: 0px;
  background: #fff;
}

A:
use this css  box-shadow: none!important;

.collapsible-header, .collapsible-body, .collapsible, ul.collapsible>li
{
  margin: 0!important;;
  padding: 0!important;
  border: 0!important;
  box-shadow: none!important;
  background: #fff;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.1/css/materialize.min.css" rel="stylesheet"/>

First

Lorem ipsum dolor sit amet.

A:

.collapsible {

  box-shadow: none;!important
}
.collapsible-header {
  border: none;!important
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet"/>

First

Lorem ipsum dolor sit amet.


text:
Q: Passing data to notification page I'm not sure what the best way of populating a notification page is. I've been using sessions to populate it with information, but this falls short if the user is blocking cookies. I've considered passing it in HTTP GET variables, but I'm unsure whether it's a good alternative since its length is limited by some browsers.
Which method do you prefer?

A: You could try using an indexed list of error messages, then simply pass the error ID as a GET parameter to the page. You can't really use POST, since I imagine you will be redirecting to the error page and therefore GET requests are pretty much your best option.
Another way of doing it is having the error page in-situ - i.e. the user stays on the same URL, but gets a modified HTTP status code (i.e. a 404 for 'not found', 500 in the event of a server error and so on) along with the error message. This way you don't have to worry about populating the page through a HTTP request, you can simply do it from within the page encountering the error.
I prefer the 2nd method, even if it is harder to implement. With it, you can then use error and exception handlers to automatically trap any error situations and then fire off your error output code.

A: There are some notifications that belong to the page that generates them, such as errors in form fields. These are easy to handle. I normally create an array to hold them in HTML format and use a function to display them as HTML list:
<?php

$errors = array();

function print_errors($errors){
    if( !empty($errors) ){
        echo '

' . implode('

', $errors) . '
';
    }
}

# ...

if($foo<=0){
    $errors[] = 'Foo is ' . htmlspecialchars($foo) . ' but it must be greater than zero.';
}

if(empty($errors)){
    save_stuff();
    header('Location: http://example.com/somewhere/else/');
    exit;
}

# ...

print_errors($errors);

echo '<form action="" method="post">';
echo '<input type="text" name="foo" value="' . htmlspecialchars($foo) . '" id="foo">';
echo '</form>';

# ...

?>

Then there is the case you describe: after a successful (or impossible) action, the user is redirected somewhere else (e.g., main section page) where he gets an explanation. For short messages, I tend to use a GET variables that hold the messages in plain text:
<?php

if( isset($_GET['error']) ){
    echo '
' . htmlspecialchars($_GET['error']) . '
';
}
if( isset($_GET['message']) ){
    echo '
' . htmlspecialchars($_GET['message']) . '
';
}

?>

This is quite fine for intranets, but it has two drawbacks:

*

*No HTML available.

*Bored users can enjoy themselves distributing links with funny error messages: http://example.com/?error=You%20are%20dumb
If you have some storage available (files, databases, whatever) you can keep full HTML messages and assign them a random ID:
ID: 4a0a19218e082a343a1b17e5333409af9d98f0f5
Date: 2010-05-25 11:24:30
Type: message
HTML: Item #25 was modified successfully.

http://example.com/?msg=4a0a19218e082a343a1b17e5333409af9d98f0f5

Make sure you save the date so you can clean up old data now and then.
My two cents.

A: There's also the possibility of appending the PHP session id to every link on the page, so you could fall back to that if cookies fail.
If that's not possible, I'd also go with saving the messages to database and passing the unique id with $_GET.


text:
Q: Class not found in aar I'm getting class not found exception in my Android library (aar) when GoogleApiAvailability is called.
    Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.GoogleApiAvailability" on path: DexPathList[[zip file "/data/app/com.myunityplugin.PushNotifications-1/base.apk"],nativeLibraryDirectories=[/data/app/com.myunityplugin.PushNotifications-1/lib/arm, /vendor/lib, /system/lib]]

The error is self-explanatory, but I'm not sure what I'm doing wrong. I'm pretty new to gradle and AndroidStudio.
I have the following under dependencies within my gradle.build:
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.google.android.gms:play-services-gcm:8.4.0'

I think the problem is that the play-services library needs to be included in the aar, and compile doesn't do that. I tried using 'runtime' but I get "gradle dsl runtime not found".
Questions:

*

*Is this an issue where I need to include the play-services library in my aar, and how do I accomplish that? (if not, how do I address this problem)

*Do I need to specify play-services or does play-services-gcm suffice?

Error Info / Setup
Line causing the error
GoogleApiAvailability ServiceAvailability = GoogleApiAvailability.getInstance();

Exception:
05-23 05:38:48.221 28055-28055/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myunityplugin.PushNotifications, PID: 28055
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/GoogleApiAvailability;
   at com.myplugin.unitynotification.GCM.GCM.checkPlayServices(GCM.java:33)
   at com.myplugin.unitynotification.GCM.MainActivity.onCreate(MainActivity.java:80)
   at android.app.Activity.performCreate(Activity.java:6550)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1120)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3108)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3263)
   at android.app.ActivityThread.access$1000(ActivityThread.java:197)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:145)
   at android.app.ActivityThread.main(ActivityThread.java:6897)
   at java.lang.reflect.Method.invoke(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.GoogleApiAvailability" on path: DexPathList[[zip file "/data/app/com.myunityplugin.PushNotifications-1/base.apk"],nativeLibraryDirectories=[/data/app/com.myunityplugin.PushNotifications-1/lib/arm, /vendor/lib, /system/lib]]
   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
   at com.myplugin.unitynotification.GCM.GCM.checkPlayServices(GCM.java:33)
   at com.myplugin.unitynotification.GCM.MainActivity.onCreate(MainActivity.java:80)
   at android.app.Activity.performCreate(Activity.java:6550)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1120)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3108)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3263)
   at android.app.ActivityThread.access$1000(ActivityThread.java:197)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:145)
   at android.app.ActivityThread.main(ActivityThread.java:6897)
   at java.lang.reflect.Method.invoke(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
    Suppressed: java.lang.ClassNotFoundException: com.google.android.gms.common.GoogleApiAvailability
   at java.lang.Class.classForName(Native Method)
   at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
   at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
        ... 16 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

App Level build.gradle
apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.google.android.gms:play-services-gcm:8.4.0'
    provided files('lib-not-include/classes.jar')
}

Project level gradle.build
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

A: The aar file doesn't contain the nested (or transitive) dependencies and doesn't have a pom file which describes the dependencies used by the library.
It means that, if you are importing a aar file using a flatDir repo you have to specify the dependencies also in your project.
You should use a maven repository (you have to publish the library in a private or public maven repo), you will not have the same issue.
In this case, gradle downloads the dependencies using the pom file which will contains the dependencies list.


text:
Q: SSD does not initialize and does not appear on "This PC" I have an issue with an SSD (Samsung 850 evo 250 Gb) that I removed from an old PC and I wanted to use it as external SSD.
This was the main SSD of the older PC, where C:\ partition was, and on which an OS is installed (Windows 8.1). I did not format the SSD beforehand, and this is likely the root of my issues.
When I try to connect the SSD to my new laptop (Microsoft Surface Book 2) with an USB cable the SSD does not show up on "This PC".
The main problem that I can think of is that now there would be two partitions labeled as "C:\", and somehow "C" cannot be automatically relabeled by Windows 10.
To see if I could see the SSD in the BIOS, I connected the SSD while the laptop was turned off, and then I turned it on. However, W10 got stuck at the initial logo, probably due to boot issues related to the "double C:\" presence.
Finally, I noticed that the SSD does show up only in device manager, listed among the other internal storage media.
If I open Disk Management, after approximately 15 minutes recognizes the SSD as unallocated and not initialized Disk. (Disk 3 in the screenshot attached).
disk management screenshot
However, I am unable to initialize it (as GPT or MBR) since I get the error:
"The request could not be performed because of an I/O error".
The related Windows Log event is:
VDS fails to write boot code on a disk during clean operation. Error code: 8007045D@02070008
  <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
  <Provider Name="Virtual Disk Service" />
  <EventID Qualifiers="49664">10</EventID>
  <Level>2</Level>
  <Task>0</Task>
  <Keywords>0x80000000000000</Keywords>
  <TimeCreated SystemTime="2020-01-11T17:15:00.383873600Z" />
  <EventRecordID>10732</EventRecordID>
  <Channel>System</Channel>
  <Computer>XXX</Computer>
  <Security />
  </System>
  <EventData>
  <Data>8007045D@02070008</Data>
  </EventData>
  </Event>

I also tried by launching diskpart from the prompt and execute the following commands:
list disk
select disk
clean

which were successful.
However, when I type
convert gpt

or
create partition primary

I get the same I/O error.
Do you have any tips on how to solve this problem considering that I do not have the old laptop anymore?
Thank you very much!
UPDATE: I re-inserted the SSD in my old laptop (directly in the second hard-drive bay, so directly with the SATA connection to the motherboard, and not as main hard drive anymore), and it was perfectly recognized. I was able to convert it to GPT and format it (NTFS).
Therefore, I thought it was a cable problem, and I bought a hard-drive box for SSDs and new cable .
However, when re-connected it with the new cable (SATA-USB) to the new laptop, the issue was again there: visible only in Disk Management as unallocated space, to be initialized. The initialization failed with the same I/O error as reported before.
I tried also to connect it to a third laptop, and the issue was exactly the same.
Can it be possible that the problem is present when the SSD is connected through a USB connection and not through the SATA? However, I would probably exclude a cable problem since I tried already two different ones.

A: The problem is certainly not related to the drive lettering as each Windows installation keeps track of drive letters on its own - connecting a C: drive from one PC to another PC will not cause that drive to conflict with the PC's original C: drive.
If the drive was working properly when removed from the old PC, the issue is most likely with your "USB cable" you mentioned. I'm assuming this is a SATA SSD - if possible, it may be worthwhile to install the SSD directly into a desktop PC to test it (SATA cable directly to the motherboard) instead of using your USB adapter for it. Alternatively, purchase a new USB to SATA adapter that has good ratings and test it with that.
If a new adapter and/or trying it in a desktop PC doesn't work, odds are that the drive was corrupted in such a way that it is going to be impossible or nearly impossible to use.
Update: As the question mentioned, the drive was from a laptop. A new USB adapter did NOT solve the issue. In this case, the laptop had a drive encryption security feature that was enabled and preventing the drive from being used in another PC.

A: In this SSD there was a Drive Lock password set. The same hold for the other HHD that now it is used for the boot of my old laptop. Therefore, I could not discover it until I checked that in the BIOS.
When connected through the SATA-USB cable, it was impossible to spot since the SSD was not even initialized in the laptop where the Drive Lock has been set.
Once the Drive Lock password has been removed, the SSD worked as it should.


text:
Q: Django: triggering a change on template I have an event app written in Django / uwsgi / nginx.
A user makes a reservation, and it shows up in his "my reservations" page. For each event he can click on a check-in button, which checks him in.
The event organizer also has a "my events" page that lists who has registered for the event and whether or not they've checked in.
What I want is as follows,

*

*The user clicks on "check-in"

*The system records the check-in

*When the event organizer is LOOKING at his "my events" page, just as the check-in happens, his page updates to show that a particular user has checked in.

How do I make this happen? How do I tell the organizer's "my events" template to update just after the user checks-in on his reservation?
Seems like I need something on the template that's "listening" to some kind of a database update (say the check-in table)? How would I do this? Is this even possible?
Thanks!!


text:
Q: Switch case statement with member variable in case I am trying to find a way to evaluate a switch-case statement using a member variable in the case part. I thought that having a global static variable like below would be allowed as const-expression.
Unfortunately the compiler tells me the opposite:
error: 'll' cannot appear in a constant-expression
error: '.' cannot appear in a constant-expression

Is there any keyword or anything that would allow this idea to work?
I am not an expert of C++11, and I heard about constexpr.
enum MyEnum2 {A=0, B=1};

class Test{
    public:
        operator MyEnum2 () { return val_;}
        Test(MyEnum2 val) :val_(val) {}
        Test() {}
        static const MyEnum2 A;
        static const MyEnum2 B;
        MyEnum2 val_;
};

const MyEnum2 Test::A(MyEnum2::A);
const MyEnum2 Test::B(MyEnum2::B);

static const Test ll;

int main() {
    class Test v = ll.A;
    cout << v << endl;
    switch(v) {
        case ll.A:
            cout << "A" << endl;
            break;

        case ll.B:
            cout << "B" << endl;
            break;
    }
}

A: Static elements are parts of the class and not of the instance.
So you have to write:
case Test::A:

Because the value in a case expression must be a constant expression, you can also use a
constexpr method like this:
class A
{
    public:
        constexpr int X() { return 42; }
};

int main()
{
    int i=42;
    A a;

    switch (i)
    {
        case a.X():
            ;

    }
}

Edit to answer questions:
You can make a constexpr object of a class which can be instantiated as constexpr which simply needs a constexpr constructor like the following:
#include <iostream>

using namespace std;

const int i = 9;    // using a const variable as compile time const

class Y             // using a class containing const vals
{
    public:
    int i;
    constexpr Y(int _i): i(_i){}
};

constexpr Y y(100);

int main()
{
    int var=9;

    switch (var)
    {
        case i:
            ;

        case y.i:
            ;
    }
}

But I can see not any real use case for this kind of programming. The switch statement can not be "reused" with an other instance, because you can not give a switch expression a other "object" of constants to behave different. So you simple hide your constant values in a very special way which is maybe not so nice for others to read.
Can you give us your use case please?

A: Simply enclose your enumeration in the class. You will get the same syntax and enums are definitions, hence const by default.
#include <iostream>
using namespace std;

class Test {
    public:
        enum MyEnum2 {
            A,
            B
        };

        Test(Test::MyEnum2 type) {
            this->type = type;
        }

        MyEnum2 type;
};

int main() {
    Test t = Test(Test::A);

    switch (t.type) {

        case (Test::A):
            cout << "A" << endl;
            break;

        case (Test::B):
            cout << "B" << endl;
            break;
    }
}

A: Add a cast operator in Test class as operator int() so that Test object gets type casted to an int


text:
Q: Counting All Character Occurrences in a Text File in C I'm trying to count all the character occurrences in a text file, but the output I get is the occurrence output line by line.
I.e.,
Text file:
aaaaAAA
a
a

Output for the file above
O caracter 'a' aparece 4 vez(es)
O caracter 'a' aparece 1 vez(es)
O caracter 'a' aparece 1 vez(es)

Translation: the character 'a' appears 4 time(s)
What I want is this:
O caracter 'a' aparece 6 vez(es)
O caracter 'A' aparece 3 vez(es)

Code:
 int strcountc(char *text, char c){
    int i, n=0;
    for(i=0; text[i]!='\0'; i++)
        if(text[i]==c)
            n++;
    return n;
}

int main(void)
{
  FILE *ficheiro1;
  char texto_str[3000];

  ficheiro1 = fopen("encrypted_file.txt", "r");

  while(fgets(texto_str, 3000, ficheiro1) != NULL)

printf("O caracter 'a' aparece %d vez(es)\n", strcountc(texto_str,'a' ));

  fclose(ficheiro1);
  return (0);
}

A: This is because of fgets() . It considers until it encounters a newline character. you are reading line by line. Either you can use static int n = 0; or do
int k = 0;

ficheiro1 = fopen("encrypted_file.txt", "r");

 while(fgets(texto_str, 3000, ficheiro1) != NULL)
    {
            k = k +strcountc(texto_str,'a' );
    }

    printf("no of char\t %d", k);

A: In each iteration you set value of n to 0 in the function call which will not give you the count of number of characters.
You should make it
static int n=0;

if you want to keep count of all occurrences of a in your file.


text:
Q: How to store row_number() results in same table column Here is the original table.
  DocumentID    FileName    Folder  OwnerOrg    DuplicateName   Identifire
D001    abc.sldasm  \\abc\\ Demo
D002    abc.sldprt  \\abc\\ Demo
D003    abc.sldprt  \\abc_another\\ Demo
D005    abc.sldprt  \\pqr_another\\ Demo
D006    kfy.sldasm  \\kfy\\ Demo
D007    kfy.sldprt  \\abc\\ Demo
D008    kfy.sldprt  \\abc_another2\\    Demo
D009    kfy.sldprt  \\xyz_another\\ Demo
D010    kfy.sldprt  \\kfy\\ Demo
D011    pny.sldasm  \\pny\\ Demo
D012    pny.sldasm  \\pny_another1\\    Demo
D013    pny.slddrw  \\abc\\ Demo
D014    pny.sldasm  \\abc_another\\ Demo
D015    pny.sldasm  \\xyz_another\\ Demo
D016    pny.sldasm  \\pny_another2\\    Demo
D017    stu.sldprt  \\abc_another\\ Demo
D018    xyz.sldprt  \\abc\\ Demo
D019    xyz.sldprt  \\abc_another\\ Demo
D020    xyz.sldprt  \\xyz_another\\ Demo

which i get the results from row_number() function in Duplicate column
My query is
Select *
From
    (Select
         Row_Number() Over (Partition By FileName Order By Folder) As Duplicate,
         *
     From
         Documents) t1
Where
    t1.Duplicate > 1
Order By
    FileName;

These are the results:
Duplicate   DocumentID  FileName    Folder              OwnerOrg    DuplicateName   Identifire
-----------------------------------------------------------------------------------------------
2           D003        abc.sldprt  \\abc_another\\     Demo
3           D005        abc.sldprt  \\pqr_another\\     Demo
2           D008        kfy.sldprt  \\abc_another2\\    Demo
3           D010        kfy.sldprt  \\kfy\\             Demo
4           D009        kfy.sldprt  \\xyz_another\\     Demo
2           D011        pny.sldasm  \\pny\\             Demo
3           D012        pny.sldasm  \\pny_another1\\    Demo
4           D016        pny.sldasm  \\pny_another2\\    Demo
5           D015        pny.sldasm  \\xyz_another\\     Demo
2           D019        xyz.sldprt  \\abc_another\\     Demo
3           D020        xyz.sldprt  \\xyz_another\\     Demo

Now I want to store the result of row_number values into DuplicateName column as Demo_<Row_number()> result wherever row_number() is > 1 in same table column DuplicateName
Desired result
Duplicate   DocumentID  FileName    Folder              OwnerOrg    DuplicateName   Identifire
-----------------------------------------------------------------------------------------------
2           D003        abc.sldprt  \\abc_another\\     Demo    Demo_2
3           D005        abc.sldprt  \\pqr_another\\     Demo    Demo_3
2           D008        kfy.sldprt  \\abc_another2\\    Demo    Demo_2
3           D010        kfy.sldprt  \\kfy\\             Demo    Demo_3
4           D009        kfy.sldprt  \\xyz_another\\     Demo    Demo_4
2           D011        pny.sldasm  \\pny\\             Demo    Demo_2
3           D012        pny.sldasm  \\pny_another1\\    Demo    Demo_3
4           D016        pny.sldasm  \\pny_another2\\    Demo    Demo_4
5           D015        pny.sldasm  \\xyz_another\\     Demo    Demo_5
2           D019        xyz.sldprt  \\abc_another\\     Demo    Demo_2
3           D020        xyz.sldprt  \\xyz_another\\     Demo    Demo_3

A: use subquery
select * from ( your query
               ) a where a.row_number>1

A: Do you just want to concatenate the result of row_number() to a string?
Select t1.*,
       replace('Demo_[n]', '[n]', seqnum) as identifire
From (Select Row_Number() Over (Partition By FileName Order By Folder) As seqnum,
           t1.*
      From Documents
     ) t1
Where t1.seqnum > 1
Order By FileName;


text:
Q: DSE Search - SOLR HTTP connection - fail-over,loadbalancing We want to use DSE Search from  Datastax in our application.
We have Cassandra on all nodes and SOLR on half of the nodes.
We can connect to one SOLR instance
  @Bean
  public SolrServer solrServer() {
    String solrHost = environment.getRequiredProperty(SOLR_HOST);
    return new HttpSolrServer(solrHost);
  }

We would like to connect to SOLR in order to have load balancing and failover similar to the connection to SOLR Cloud :
  @Bean
  public SolrServer solrServer() throws MalformedURLException {
    return new CloudSolrServer(environment.getRequiredProperty(ZK_HOST),
            new LBHttpSolrServer(
                    environment.getRequiredProperty(SOLR_HOST1),
                    environment.getRequiredProperty(SOLR_HOST2),
                    environment.getRequiredProperty(SOLR_HOST3)));
  }

Is something like this possible with DSE Search?


text:
Q: Grid result not match the export result in magento 2 I created a module for some data logging with widget grid display and csv export function.
Inside the collection, I added a new columns with mysql function "IF(DATE_FORMAT(updated_at,'%H:%i') = '16:30',DATE_FORMAT(updated_at,'%Y-%m-%d'),'')"
The result is correct in the exported csv but not for grid.

A: First of all, your Magento do NOTHING wrong.
Most probably you didn't set the correct timezone in DB. If you didn't set it, the time will be treated as UTC. And you definitely set GMT+8 in Magento, so you can notice that the time in Magento is 8 hours greater than the time in CSV.
For DB side, check the timezone setting first by running this SQL:
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);

If it returns 00:00:00 it means your timezone is set to UTC on DB side. To fix it, run this command:
SET time_zone = 'Asia/Hong_Kong';

Of course, you may need to re-import the products if the time doesn't show correctly.


text:
Q: Expand and Collapse with multiple buttons and divs I need help in collapsing the divs when the button is clicked again.
I have this code:

$('#btn1').click(function() {
  $('.collapse').hide();
  $('#demo').show();
});
$('#btn2').click(function() {
  $('.collapse').hide();
  $('#demo1').show();
});

  <button type="button" class="btn btn-default" data-toggle="collapse" data- target="#demo" id="btn1">Company Details</button>
  <button type="button" class="btn btn-default" data-toggle="collapse" data- target="#demo1" id="btn2">Commercial Details</button>

    1st div

    2nd div

From here: Bootstrap Collapse with multiple button and div
This code works and hides div1 when the button2 is clicked and expands div2 but it does not hide the div2 when button2 is clicked again.
Is there a way to show div1 when button1 is clicked and hide the div1 when button2 is clicked and expand div2. But when button2 is clicked again, it hides div2 and hence all the collapsible divs are collapsed and this behaviour works with button1 and div1 too.

A:

$('#btn1').click(function(){
 // $('.collapse').hide();
  $('#demo1').hide();
  $('#demo').show();
});
$('#btn2').click(function(){
  //$('.collapse').hide();
  $('#demo').hide();
  $('#demo1').show();
});

    <button type="button" class="btn btn-default" data-toggle="collapse" data-
    target="#demo" id="btn1" >Company Details</button>
      <button type="button" class="btn btn-default" data-toggle="collapse" data-
    target="#demo1" id="btn2">Commercial Details</button>

        1st div

        2nd div

A: Update your script like this
$('#btn1').click(function(){

      if($('#demo').is(':visible')){
           $('#demo').hide();
      }else{
          $('#demo1').hide();
          $('#demo').show();

      }

    });
    $('#btn2').click(function(){

      if($('#demo1').is(':visible')){
           $('#demo1').hide();
      }else{
           $('#demo').hide();
          $('#demo1').show();
      }
    });

A: I will suggest you to hide both the div at first and then you can use toggle
Stack Snippet

$('#demo1,#demo').hide()
$('#btn1').click(function() {
  $('#demo1').hide();
  $('#demo').toggle();
});
$('#btn2').click(function() {
  $('#demo').hide();
  $('#demo1').toggle();
});

  <button type="button" class="btn btn-default" data-toggle="collapse" data- target="#demo" id="btn1">Company Details</button>
  <button type="button" class="btn btn-default" data-toggle="collapse" data- target="#demo1" id="btn2">Commercial Details</button>

    1st div

    2nd div


text:
Q: application of stone weierstrass theorem1 Assume that the function $f:[0,\infty)\Rightarrow \mathbb{R}$ is a continuous bounded function. Then $f$ is identically equal to zero if $\int_0^\infty f(x)\exp(-nx)=0$ for all $n=1,2,\cdots$.

A: Hint: Make the change of variables $x= -\ln u.$ Then the condition is that
$$\int_0^1 f(-\ln u)\cdot u^n\cdot (1/u)\,du = 0,\, n = 1,2,\dots,$$
which implies $\int_0^1 f(-\ln u)\cdot u^n\,du = 0, n = 0,1,\dots.$ This in turn implies $\int_0^1 f(-\ln u)p(u)\,du = 0$ for every polynomial $p.$


text:
Q: Are Cloud Endpoints with Go Google App Engine Standard possible? I have implemented a simple API in Go on Google App Engine Standard using just:
func init() {
    http.HandleFunc("/api/v1/resource",submitResource)
}

Nothing special. However I want to port this code to using Cloud Endpoints instead in order to get the better monitoring and diagnostics.
Is it even possible with STANDARD instances or must I move to FLEXIBLE?
I can't find any documentation on this. Nor answers to this seemingly simple question. At the moment I half wish I had chosen Python because its support seems more mature. I chose Go because it seems more appropriate for API-like code because my minimal research suggested Go offered better performance.
If it is possible, are there any pointers to how please?

A: Only Python and Java are supported on GAE Standard via the Endpoints Frameworks. However, Go is supported on GAE Flexible.
Here is the Go GAE Flexible sample:
https://github.com/GoogleCloudPlatform/golang-samples/tree/master/endpoints/getting-started

A: After much research and trial and error, the simple answer is "No." - as of Dec 2016.
The longer answer is it's possible if you want to put far too much effort into making up to date libraries of your own. There is basically no support, even in alpha, for the current Google Cloud Endpoints using Go with Google App Engine Standard.

A: It's possible to run Go+endpoints on GAE Standard environment, however libraries might be outdated now.
Libraries and sample app can be found on github:
https://github.com/GoogleCloudPlatform/go-endpoints
I have successfully deployed "Greetings" as AppEngine SE app, and it works.


text:
Q: Python Requests Stream Async I am trying to download large file from python requests library by setting the stream=True
But i want this function to be executed asynchronously and send response back to server with downloading in the background.
Here is my code
async def downloadFile(url, filename):
  r = requests.get(url, stream=True)
  with open(os.path.join('./files', filename), 'wb+') as f:
    for chunk in r.iter_content(chunk_size=1024):
        if chunk:
            f.write(chunk)
  # Creating same file name
  # with _done appended to know that file has been downloaded
  with open(os.path.join('./files', filename + '_done'), 'w+') as f:
    f.close()
  await asyncio.sleep(1)

Calling this function from other function like this
# check if file exist in server
        if(os.path.exists(os.path.join('./files', fileName))):

            #file exist!!!

            #check if done file exist
            if(os.path.exists(os.path.join('./files', fileName + '_done'))):

                #done file exist
                self.redirect(self.request.protocol + "://" +
                              self.request.host + '/files/' + fileName)
            else:
                #done file not exist. Wait for 5 min more

                self.write('Wait 5 min')
                self.finish()
        else:
            # file doesnt exist. Initiate download
            self.write('Wait 5 min')
            self.finish()
            d = asyncio.ensure_future(downloadFile(
                fileRes, fileName))
            # loop = asyncio.get_event_loop()
            # loop.run_until_complete(d)

The problem is that the file is created but its size remains 0 and the file appended "_done" is never created.
What am I doing wrong here?

A: Your code works for me. Maybe is it the resource you're trying to get that does not work.
You might want to try enabling debug for requests as suggested by @brennan, and/or add printouts to your code to follow what's happening:
>>> import requests
>>> import asyncio
>>>
>>>
>>> async def downloadFile(url, filename):
...   print(f"• downloadFile({url}, {filename})")
...   r = requests.get(url, stream=True)
...   print(f" → r: {r}")
...   with open(os.path.join('./files', filename), 'wb+') as f:
...     print(f" → f is opened: {f}")
...     for chunk in r.iter_content(chunk_size=1024):
...         print(f"  → chunk is: {chunk}")
...         if chunk:
...             f.write(chunk)
...   # Creating same file name
...   # with _done appended to know that file has been downloaded
...   with open(os.path.join('./files', filename + '_done'), 'w+') as f:
...     print(f" → creating output with _done")
...     f.close()
...   print(f" → wait 1")
...   await asyncio.sleep(1)
...
>>>
>>>
>>> d = asyncio.ensure_future(downloadFile('https://xxx/yyy.jpg', 'test.jpg'))
>>> loop = asyncio.get_event_loop()
>>> loop.run_until_complete(d)
• downloadFile(https://xxx/yyy.jpg, test.jpg)
 → r: <Response [200]>
 → f is opened: <_io.BufferedRandom name='./files/test.jpg'>
  → chunk is: b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\r\t\n\x0b\n\x08\r\x0b\n\x0b\x0e\x0e\r\x0f\x13....'
  → chunk is: ...
  ...
 → creating output with _done
 → wait 1

that would make your _done part of your code useless (you only need the printouts). And even the wait at the end (when it's done… it's done!).
async def downloadFile(url, filename):
  r = requests.get(url, stream=True)
  with open(os.path.join('./files', filename), 'wb+') as f:
    for chunk in r.iter_content(chunk_size=1024):
        if chunk:
            f.write(chunk)

Though maybe you might want to catch any possible issues happening connecting to the server and act accordingly:
async def downloadFile(url, filename):
  try:
    r = requests.get(url, stream=True)
    r.raise_for_status() # to raise on invalid statuses
    with open(os.path.join('./files', filename), 'wb+') as f:
      for chunk in r.iter_content(chunk_size=1024):
          if chunk:
              f.write(chunk)
  except requests.RequestException as err:
    # do something smart when that exception occurs!
    print(f"Exception has occured: {err}")


text:
Q: How to automatically run the executable in GDB? I'd like to have gdb immediately run the executable, as if I'd typed "run"
(motivation: I dislike typing "run").
One way is to pipe the command to gdb like this:
$ echo run | gdb myApp

But the problem with this approach is that you lose interactivity with gdb,
eg. if a breakpoint triggers or myApp crashes, gdb quits.
This method is discussed here.
Looking at the options in --help, I don't see a way to do this, but perhaps I'm missing something.

A: start command
This command is another good option:
gdb -ex start --args ./a.out arg1 arg2

It is like run, but also sets a temporary breakpoint at main and stops there.
This temporary breakpoint is deactivated once it is hit.
starti
There is also a related starti which starts the program and stops at the very first instruction instead, see also: Stopping at the first machine code instruction in GDB
Great when you are doing some low level stuff.

A: gdb -x <(echo run) --args $program $args

A: I would use a gdb-script:
gdb -x your-script

where your-script contains something like:
file a.out
b main
r

afterwards you have the normal interactive gdb prompt
EDIT:
here is an optimization for the truly lazy:

*

*save the script as .gdbinit in the working directory.

*Afterwards you simply run gdb as
gdb
... and gdb automatically loads and executes the content of .gdbinit.

A: (echo r ; cat) | gdb a.out

The cat allows you keep typing after gdb breaks.

A: gdb -ex run ./a.out

If you need to pass arguments to a.out:
gdb -ex run --args ./a.out arg1 arg2 ...

EDIT:
Orion says this doesn't work on Mac OSX.
The -ex flag has been available since GDB-6.4 (released in 2005), but OSX uses Apple's fork of GDB, and the latest XCode for Leopard contains GDB 6.3.50-20050815 (Apple version gdb-967), so you are out of luck.
Building current GDB-7.0.1 release is one possible solution. Just be sure to read this.


text:
Q: Converting pandas dataframe to structured arrays I have the following pandas dataframe
import pandas as pd
a = [2.5,3.3]
b = [3.6,3.9]
D = {'A': a, 'B': b}

which gives me something like
+---+-----+-----+
|   |  A  |  B  |
+---+-----+-----+
| 0 | 2.5 | 3.3 |
| 1 | 3.6 | 3.9 |
+---+-----+-----+

I want to convert this dataframe to a structured array like
data = np.rec.array([
('A', 2.5),
('A', 3.6),
('B', 3.3),
('B', 3.9),
], dtype = [('Type','|U5'),('Value', '<i8')])

I failed to find a way to make this happen since I'm new to pandas. I tried pd.to_records but the index is getting in the way and I cannot find a way around that.
Any help is appreciated. Thanks.

A: Melt the DataFrame to make A and B (the column index) into a column.
To get rid of the numeric index, make this new column the index. Then call to_records():
import pandas as pd
a = [2.5,3.3]
b = [3.6,3.9]
D = {'A': a, 'B': b}
df = pd.DataFrame(D)
result = (pd.melt(df, var_name='Type', value_name='Value')
          .set_index('Type').to_records())
print(repr(result))

yields
rec.array([('A',  2.5), ('A',  3.3), ('B',  3.6), ('B',  3.9)],
          dtype=[('Type', 'O'), ('Value', '<f8')])

This is the key step:
In [167]: df
Out[167]:
     A    B
0  2.5  3.6
1  3.3  3.9

In [168]: pd.melt(df)
Out[168]:
  variable  value
0        A    2.5
1        A    3.3
2        B    3.6
3        B    3.9

Once you've melted the DataFrame, to_records (basically) returns the desired result:
In [169]: pd.melt(df).to_records()
Out[169]:
rec.array([(0, 'A',  2.5), (1, 'A',  3.3), (2, 'B',  3.6), (3, 'B',  3.9)],
          dtype=[('index', '<i8'), ('variable', 'O'), ('value', '<f8')])

A: np.rec.fromrecords(list(zip(df.melt().variable,df.melt().value)))
Out[531]:
rec.array([('A',  2.5), ('A',  3.3), ('B',  3.6), ('B',  3.9)],
          dtype=[('f0', '<U1'), ('f1', '<f8')])

A: works for me without melting
pandas Version: 1.5.2, numpy Version: 1.23.5, python 3.10.4
records = df.to_records(index=False)
data = np.array(records, dtype = records.dtype.descr)

A: You can melt and call to_records:
pd.melt(df).to_records(index=False)


text:
Q: Code blocks MinGW and the %n conversion character I am trying to use a conversion character to count the number of chars printed so far with the following code.
#include <stdio.h>
int main(void) {
    int n;
    printf("%s: %nFoo\n", "hello", &n);
    printf("%*sBar\n", n, "");
}

When working correctly this code prints Hello Foo, then on the next line Bar is aligned with Foo.
This works fine when compiled with GCC on my linux box. However, when compiled using minGW in code blocks on my Windows PC %n does not work, and all that is printed is hello: Bar all on one line. Why so and can I fix this?

A: use compile option -D__USE_MINGW_ANSI_STDIO
E.g
>gcc prog.c -D__USE_MINGW_ANSI_STDIO

or
>clang prog.c -D__USE_MINGW_ANSI_STDIO

Another solution is placing this command above the first import statement like so (see below). This will ensure that the ANSI I/O standards are preferred over Microsoft's. More information in this link here.
#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>

A: It looks like this is a Windows issue, this article says:

The default C-RunTime Library (msvcrt.dll) on Vista seems to have %n disabled by default - security reasons of course

It looks like there is a _set_printf_count_output to enable it.
BLUEPIXY found that in order to get it working outside Visual Studio you need to define __USE_MINGW_ANSI_STDIO:
#define __USE_MINGW_ANSI_STDIO 1


text:
Q: How to determine iTextSharp Basefont default style I am creating a PDF using iTextSharp.
Part of the process adds straightforward text to the PDF and another part creates an outline of the same text.
For the straighforward text aspect I am using the ShowTextAligned method in iTextSharp; which requires a Basefont and has no way of setting the style.
For the outline I am creating a GDI GraphicsPath to get points, which are then translated into PDF curves/lines etc. The AddString method requires a Drawing.FontStyle
Now my issue is that I need to set the style of AddString to the same one being used by the BaseFont. I.E if the Basefont is rendering Regular, i need to set the AddString fontstyle to regular
How do I determine what style is being used by the BaseFont in ShowTextAligned?
Further info:
I have also tried using ColumnText; which allows you to set an iTextSharp Font, along with it's style. Though using this method results in a font that is rendered with the approximate style; I.E a font usually in regular and set to bold gives a slightly malformed bold font.
EDIT
When I say i need to pass in the BaseFont to ShowTextAligned, What I mean to say is that in order to use this method you have to set the font and size first using SetFontAndSize of the PdfContentByte - it is this method that requires the BaseFont.
I know I must be missing something obvious.. I just can't see the wood for the trees :)

A: You can try defining your base font beforehand and use it throughout your PDF doc.
See iTextSharp - Working with Fonts
Sample code:
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);

Font times = new Font(bfTimes, 12, Font.ITALIC, Color.RED);

The above lines create a BaseFont object and uses the built-in constant values to set the font family and encoding. It also specifies false for embedding the font within the PDF document. A new Font object is created using the BaseFont object, and further setting the font size in points, the style and the color - again, using iTextSharp's constants for these values.
For more info on BaseFont, see its class definition.

A: You can use SetColorFill method. Like this
content.BeginText();
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
content.SetFontAndSizebaseFont, 12);
BaseColor baseColor = new BaseColor(255, 0, 0);
content.SetColorFill(baseColor);
//or use predefined colors
content.SetColorFill(BaseColor.RED);
// use ShowTextAligned method
content.EndText();


text:
Q: Make YouTube video autoplay using React I am trying to make my video autoplay using react. adding autoplay=1 as a parameter doesn't work. Any suggestions?`
Here is my code.
<div
  className="video mt-5"
  style={{
         position: "relative",
         paddingBottom: "56.25%" /* 16:9 */,
         paddingTop: 25,
         height: 0
       }}
>
    <iframe
       style={{
             position: "absolute",
             top: 0,
             left: 0,
             width: "100%",
             height: "100%"
             }}
        src={'https://www.youtube.com/embed/hEnr6Ewpu_U?'}
        frameBorder="0"
    />
</div>

A: According to 2018 changes in youtube policies, they've omitted option to autoplay videos with sound. If you want to autoplay it muted, there's still an option to do it with an iframe:
<iframe src='https://www.youtube.com/embed/hEnr6Ewpu_U?autoplay=1&mute=1'
        frameBorder='0'
        allow='autoplay; encrypted-media'
        allowFullScreen
        title='video'
/>

A: I wouldn't use <iframe> cuz when you go to Youtube you still have to click to play. I would use a library called react-player
import ReactPlayer from "react-player";

<ReactPlayer
  url={props.url}
  playing={true}
  width={props.width}
  height={props.height}
/>

And it will autoplay :)

A: This solved it for me
If you are using <video> in react

*

*Use autoPlay instead of autoplay for react.

*Also add muted
<video autoPlay muted src="/vid.mp4" />
if you want to use the autoplay with small letters, you should assign the value autoplay="true"


text:
Q: Passing more than 1 variable of different type within an AsyncTask I have an AsyncTask, and in doInBackground (), I wish to call publishProgress() and pass it more than 1 variable, of different types, say, a String and an Integer. How can I do this? I tried to define onProgressUpdate(Object... values) and then call it via publishProgress(StringVar, IntVar), and then in onProgressUpdate(), I tried to access them via values[0] and values[1] but that didn't work.
How can I achieve this?
Thanks.

A: The easiest way to do this would probably be to define a wrapper class that takes a string and an integer. Then create an async task that uses this wrapper for its progress udpates.
public class Wrapper{
    public final String mString;
    public final Integer mInteger;

    public Wrapper(String myString, Integer myInteger){
        mString = myString;
        mInteger = myInteger;
    }
}

A: Use a class to wrap your progress values:
class ProgressUpdate {
    public final String detail;
    public final int value;

    public ProgressUpdate(String detail, int value) {
        this.detail = detail;
        this.value = value;
    }
}

Then, publish your progress:
publishProgress(new ProgressUpdate(detail, value));


text:
Q: What does the method `method` do in `&Unit.method(:new)`? I'm new to the Rails and trying to figure out the code that im given. What does the method method do in  &Unit.method(:new) ? And what is the meaning of &? There's not method method in Unit model and wondering why it can be there. And lastly, I guess the symbol :new creates a new object of Unit ?
class Unit
  include ActiveModel::Model

  attr_accessor :number
end

class Product
  include ActiveModel::Model
  .........
  .........
  def units=(values)
    @units = values.map(&Unit.method(:new))
  end
end

A: The method method is defined in the class Object and thus available on all objects. It takes as its argument the name of a method and returns a Method object that can be used to reflect on or call the given method.
So Unit.method(:new) gives you a Method object that represents the method Unit.new.
Now the unary & operator takes a Proc object or something that can be converted to a Proc using to_proc (which Method objects can) and then converts it to block.
So &Unit.method(:new) creates a block that calls the Unit.new method, making values.map(&Unit.method(:new)) equivalent to:
values.map do |value|
  Unit.new(value)
end


text:
Q: Problem with initializing a type with WinsdorContainer     public ApplicationView(string[] args)
    {
        InitializeComponent();

        string configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config");
        FileInfo configFileInfo = new FileInfo(configFilePath);
        XmlConfigurator.ConfigureAndWatch(configFileInfo);

        IConfigurationSource configSource = ConfigurationManager.GetSection("ActiveRecord") as IConfigurationSource;
        Assembly assembly = Assembly.Load("Danel.Nursing.Model");
        ActiveRecordStarter.Initialize(assembly, configSource);

        WindsorContainer windsorContainer = ApplicationUtils.GetWindsorContainer();
        windsorContainer.Kernel.AddComponentInstance<ApplicationView>(this);
        windsorContainer.Kernel.AddComponent(typeof(ApplicationController).Name, typeof(ApplicationController));
        controller = windsorContainer.Resolve<ApplicationController>(); // exception is thrown here

        OnApplicationLoad(args);
    }

The stack trace is this:

Castle.MicroKernel.ComponentActivator.ComponentActivatorException
  was unhandled
  Message="ComponentActivator: could not
  instantiate
  Danel.Nursing.Scheduling.Actions.DataServices.NurseAbsenceDataService"
  Source="Castle.MicroKernel"
  StackTrace:
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstance(CreationContext
  context, Object[] arguments, Type[]
  signature)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext
  context)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext
  context)
         at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext
  context)
         at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveServiceDependency(CreationContext
  context, ComponentModel model,
  DependencyModel dependency)
         at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext
  context, ISubDependencyResolver
  parentResolver, ComponentModel model,
  DependencyModel dependency)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate
  constructor, CreationContext context,
  Type[]& signature)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext
  context)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext
  context)
         at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext
  context)
         at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveServiceDependency(CreationContext
  context, ComponentModel model,
  DependencyModel dependency)
         at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext
  context, ISubDependencyResolver
  parentResolver, ComponentModel model,
  DependencyModel dependency)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate
  constructor, CreationContext context,
  Type[]& signature)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext
  context)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext
  context)
         at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext
  context)
         at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveServiceDependency(CreationContext
  context, ComponentModel model,
  DependencyModel dependency)
         at Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext
  context, ISubDependencyResolver
  parentResolver, ComponentModel model,
  DependencyModel dependency)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate
  constructor, CreationContext context,
  Type[]& signature)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext
  context)
         at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext
  context)
         at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext
  context)
         at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext
  context)
         at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext
  context)
         at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler
  handler, Type service, IDictionary
  additionalArguments)
         at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler
  handler, Type service)
         at Castle.MicroKernel.DefaultKernel.get_Item(Type
  service)
         at Castle.Windsor.WindsorContainer.Resolve(Type
  service)
         at Castle.Windsor.WindsorContainer.ResolveT
         at Danel.Nursing.Scheduling.ApplicationView..ctor(String[]
  args) in
  E:\Agile\Scheduling\Danel.Nursing.Scheduling\ApplicationView.cs:line
  65
         at Danel.Nursing.Scheduling.Program.Main(String[]
  args) in
  E:\Agile\Scheduling\Danel.Nursing.Scheduling\Program.cs:line
  24
         at System.AppDomain._nExecuteAssembly(Assembly
  assembly, String[] args)
         at System.AppDomain.ExecuteAssembly(String
  assemblyFile, Evidence
  assemblySecurity, String[] args)
         at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
         at System.Threading.ThreadHelper.ThreadStart_Context(Object
  state)
         at System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback
  callback, Object state)
         at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
  System.ArgumentNullException
         Message="Value cannot be null.\r\nParameter name: types"
         Source="mscorlib"
         ParamName="types"
         StackTrace:
              at System.Type.GetConstructor(BindingFlags
  bindingAttr, Binder binder, Type[]
  types, ParameterModifier[] modifiers)
              at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.FastCreateInstance(Type
  implType, Object[] arguments, Type[]
  signature)
              at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstance(CreationContext
  context, Object[] arguments, Type[]
  signature)
         InnerException:

It actually says that the type that I'm trying to initialize does not exist, I think.
This is the concreate type that it complains about:
   namespace Danel.Nursing.Scheduling.Actions.DataServices
    {
        using System;
        using Helpers;
        using Rhino.Commons;
        using Danel.Nursing.Model;
        using NHibernate.Expressions;
        using System.Collections.Generic;
        using DateUtil = Danel.Nursing.Scheduling.Actions.Helpers.DateUtil;
        using Danel.Nursing.Scheduling.Actions.DataServices.Interfaces;

        public class NurseAbsenceDataService : AbstractDataService<NurseAbsence>, INurseAbsenceDataService
        {
            NurseAbsenceDataService(IRepository<NurseAbsence> repository)
                : base(repository)
            {
            }

            //...
        }
    }

The AbstractDataService only holds the IRepository for now.
Anyone got an idea why the exception is thrown?
EDIT:
The problem lays here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Danel.Nursing.Scheduling.Actions.Interfaces;
using Rhino.Commons;
using System.Reflection;
using Castle.Windsor;

namespace Danel.Nursing.Scheduling.Actions.Helpers
{
    public class DataServicesInitiator : IDataServicesInitiator
    {
        public void AddToIocContainer(ref WindsorContainer windsorContainer)
        {
            if (windsorContainer.Kernel.HasComponent(typeof(IRepository<>)) == false)
                windsorContainer.AddComponent(typeof(ARRepository<>).FullName, typeof(IRepository<>), typeof(ARRepository<>));
            foreach (Type type in Assembly.Load("Danel.Nursing.Scheduling.Actions").GetTypes())
            {
                if (type == null)
                    continue;

                if (type.Namespace != "Danel.Nursing.Scheduling.Actions.DataServices")
                    continue;

                if (type.IsAbstract || type.IsInterface)
                    continue;

                if (windsorContainer.Kernel.HasComponent(type.FullName))
                    continue;

                if (type.GetInterfaces().Length == 0)
                    windsorContainer.AddComponent(type.FullName, type);
                else
                    windsorContainer.AddComponent(type.FullName, type.GetInterfaces()[0], type);
            }
        }
    }
}

For some reason type is null although GetTypes return no null types.

A: What does the inner exception say? It looks like the constructor for the type threw an exception or it was unable to properly call the constructor for some other reason...
Update
You can get everything - ActiveRecord, Windsor with MicroKernel, DynamicProxy and NHibernate
by downloading ActiveRecord package. It's all there.
If you don't want to update you may take alternative approach - write a custom Activator for this component (inherit from the default one and override the method which exposes the bug.)
This should be the safest workaround.


text:
Q: Spring 3 IOC annotation I have the following packages hierarchy
 -org.bmark
   --dao
    --- implementations
    --- interfaces
   --services
    --- implementations
    --- interfaces

This is my web.xml
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/ApplicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
      <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

This is part of my ApplicationContext.xml
<context:annotation-config/>
<context:component-scan base-package="org.bmark.dao"/>
<context:component-scan base-package="org.bmark.services"/>

I have A UserDAO and a ContentTypeDAO (Both have implementations). I also have a UserService and a ContentTypeService (Both have implementations). The services class have the @Service annotation.
The UserDAO is @Autowired into the implementation of the UserServiceImpl and everything works good. The issue is that the ContentTypeDAO is also @Autowired into the ContentTypeServiceImpl but when i start the server i get this exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contentTypeServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.bmark.dao.intefaces.ContentTypeDAO org.bmark.services.implementations.ContentTypeServiceImpl.contentTypeDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.bmark.dao.intefaces.ContentTypeDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.bmark.dao.intefaces.ContentTypeDAO org.bmark.services.implementations.ContentTypeServiceImpl.contentTypeDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.bmark.dao.intefaces.ContentTypeDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.bmark.dao.intefaces.ContentTypeDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Why am i getting this exception on my ContentTypeDAO and not getting it with my UserDAO?
How do i fix this?

A: Try replacing
<context:component-scan base-package="org.bmark.dao"/>
<context:component-scan base-package="org.bmark.services"/>

with
<context:component-scan base-package="org.bmark.dao, org.bmark.services"/>

I'm not entirely sure if the context supports multiple component-scan definitions or if perhaps one is overriding the other.


text:
Q: Java, strange timestamp format in microsecond? How can I convert the following timestamp "2012-02-22T16:46:28.9870216+00:00" into a timestamp readable and processable by Java without losing any accuracy? what its data format?? for example about my goal, I receive 2 messages, read the timestamp in each message (as it written in my example above) compare between two timestamps to determine which is the old between them
by noting that the question below does not match what I need, it is different where they speak about timestamp format is different of 2012-02-22T16:46:28.9870216+00:00 which I did not know about it
Converting ISO 8601-compliant String to java.util.Date

A: You can parse it with this format: DateTimeFormatter.ISO_OFFSET_DATE_TIME.
public static void main(String[] args) throws IOException {
    String str = "2012-02-22T16:46:28.9870216+00:00";
    DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
    System.out.println(dtf.parse(str));
}

If you run this code, you will see on the console:
{OffsetSeconds=0, InstantSeconds=1329929188},ISO resolved to 2012-02-22T16:46:28.987021600

Update:
Here is an updated response which shows how to convert the string to a LocalDateTime and allows date comparisons:
public static void main(String[] args) throws IOException {
    String str = "2012-02-22T16:46:28.9870216+00:00";
    DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
    LocalDateTime lds = LocalDateTime.parse(str, dtf);
    System.out.println(lds);
    String str2 = "2012-02-22T16:46:28.9970430+00:00";
    String str3 = "2012-02-22T16:46:29.0270266+00:00";
    LocalDateTime lds2 = LocalDateTime.parse(str2, dtf);
    LocalDateTime lds3 = LocalDateTime.parse(str3, dtf);
    System.out.println(lds2.compareTo(lds3));
    System.out.println(lds3.compareTo(lds2));
}

Update 2:
If you want to print out a date in this format you have to use java.time.OffsetDateTime, like so:
public static void main(String[] args) throws IOException {
    OffsetDateTime now = OffsetDateTime.now();
    DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
    System.out.println(dtf.format(now));
}

This prints out:
2018-03-18T16:46:46.715Z


text:
Q: Find Missing Number from a given arithmetic progression I came across this problem where you were given a number N as Input and then N numbers followed (where 3<=N<=2500). These N numbers were part of an Arithmetic Progression (of size N+1) from which one number was removed. So the task was to find that Missing number. For instance
5
1 3 5 9 11

The output is 7
I came up with two methods, the 2nd one passing all the test cases but the first one failing in certain (hidden) cases.
First I will explain the second method
METHOD II
Let diff=(last_number-first_number)/N
 //Considering 0 based indexing
 for i=0 to (N-2)
    if( array[i+1] is not equal to (array[i]+diff))
          print (array[i]+diff)
          break

This method passed all the test cases. Now the first method which I implemented and which failed certain test cases was as follows
METHOD I
 //Considering 0 based indexing
 for i=1 to (N-2)
      if (2*array[i] is not equal to (array[i-1]+array[i+1])) then
              if( (array[i]-array[i-1])< (array[i+1]-array[i]))
                      print 2*array[i]-array[i-1]
              else
                      print 2*array[i]-array[i+1]
              break

Can anyone explain what is wrong with METHOD I?? Which cases am I missing.
Thanks.

A: Method 1 does not work when the numbers are in decreasing order.
For 7 5 1 output should be 3 but the algorithm will give 9.
Method 2 works in this case because the difference is correctly calculated as negative and the algorithm proceeds accordingly.

A: Though not answer of your original question but if you need it a better solution with O(logN) complexity for the finding the missing number(if there is only one). Use binary search .
make following comparision for binary search
  if(a[mid] != mid*(difference)+a[0]) {

        missing_num = mid*(difference) + a[0];
        search lower half
  }

  else search higher half

A: This is my solution in Ruby:
number_of_terms = gets.chomp.to_i

Get number of terms from STDIN
progression = gets.chomp.split(' ').map(&:to_i)

Get the string, remove any leading and trailing white space, split it at the spaces between the numbers and then convert each item into an integer.
expected_sum = (number_of_terms+1)/2.0*(progression.first+progression.last)

Using formula for the summation of an arithmetic progression: n/2 ( a[0] + a[n] ).
Here dividing by 2.0 is important. Need to keep precision.
actual_sum = progression.inject(:+)

Checking what was the sum of the given numbers.
missing_element = (expected_sum - actual_sum).to_i

Difference is of course the missing element. Also converting into an integer to remove trailing .0
i.e. 4.0 => 4
puts "Missing element is: #{missing_element}"

A: Works for
1) Any value of N (given 5 in example)
2) Any Difference between terms (given 2 in example)
3) Difference can be + as well as - (example: 11 5 2 -1 -4)
int diff[]= new int[length-1];
for(int i = 0; i<length-1;i++){
    diff[i] = n1[i+1]-n1[i];
    System.out.println(diff[i]);
    if(i!=0){
        if(diff[i]<diff[i-1]){
            if(diff[i]<0)
                System.out.println(n1[i]+diff[i-1]);
            else
                System.out.println(n1[i-1]+diff[i]);
            break;
        }
        if(diff[i]>diff[i-1]){
            if(diff[i]<0)
                System.out.println(n1[i-1]+diff[i]);
            else
                System.out.println(n1[i]+diff[i-1]);
            break;
        }
    }
}

n1 is where you store the number array from String.
Length is how many numbers you are providing.
This is optimized so that if you miss number in between first two numbers then it only loops 3 times no matter how many numbers you have given

A: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

int findDelta(long *x, int n);

int main(){
    int n;
        fscanf(stdin,"%d",&n);
        long *x= (long*) calloc(n,sizeof(long));
    long k;
    for(int i=0;i<n;i++){
        scanf("%ld",&k);
        x[i]=k;
    }

    int delta=findDelta(x,n);
    for(int i=0;i<n-1;i++){
        if (x[i+1]-x[i] != delta)
            printf("%ld\n",x[i]+delta);
    }
    free(x);
    return 0;
}

int findDelta(long *x, int n){
    long delta1,delta2;
    delta1=x[1]-x[0];
    int d1Count=0;
    int d2Count=0;

    for(int i=1;i<n-1;i++){
        delta2=x[i+1]-x[i];
        if(delta2==delta1)
          d1Count++;
        else
          d2Count++;
    }
    if (d1Count > d2Count)
        return (delta1);
    else
        return (delta2);
}


text:
Q: wildcard/regular expressions in List.js? I have a news page in which I would like to have buttons that filter by month, using the span class 'date'. Using list.js, I can only filter by using an exact matching string. Is there a wildcard I can use to display all items that contain the word November
HTML
<button class="btn" id="filter-oct">October</button>
<button class="btn" id="filter-nov">November</button>

News title

Thursday 31 November 2013 Some text, more text

Should you have any concerns, require additional information or wish to discuss this matter further please contact me

JS

It's on this line where it does the matching - but only matches the exact word/s
if (item.values().date == "November 2013") {
I've tried using &= and ^= to try to get a match but neither work.
Thanks


text: Q: How to get the user detail from auth0 in reactJs I have used the auth0 in react and now  I have added the additionalSignUpField in signup the define the user role. So now How I can get the user role while user logged in. Here is my auth0 lock var:enter image description here


text:
Q: Laravel find user from 2 models How can I search for user in 2 different tables?
Example:
$user =
// either
User::where('email', $request->email)->first();
// or this
Seller::where('email', $request->email)->first();

A: So look for the user existence in the first model. If not found look in the second model.
$user = User::where('email', $request->email)->first();
if (!$user) {
    $user = Seller::where('email', $request->email)->first();
}

if ($user) {
    return $user;
} else {
    return 0;
}

as Tim suggested in the comment, if you are using php 7+, you can use null coalescing operator to do it in one line
return User::where('email', $request->email)->first() ?? Seller::where('email', $request->email)->first() ?? 'not found / 0 / or anything';


text:
Q: Call a TDataModule method in TThread.Execute In general, is it possible in a TThread.Execute procedure
to call a TDataModule method, in which there is no visual activity involved?
Thanks to all, Massimo.

A: The easiest way to go is to use TThread.Synchronize to invoke a method in your data module.
However, if you do not wish to do that, even when no visual activity is involved, you should determine whether or not you need to add a critical section to protect you.
Any access to any standard or third-party VCL component, whether it is visual (TButton) or non-visual (datasets) should be considered UNSAFE.   Any access to a local data object (like a private field or global variable) must also be protected by critical sections.
Here's a direct call from a from background thread to your data module:
    if Assigned(MyDataModule) then MyDataModule.DoSomething(a,b,c);

Here's the code in your data module, which I am showing you a sample bit of code that makes sure that we are the only thread touching FList right now:
/// DoSomething: Note this method must be thread-safe!
procedure TMyDataModule.DoSomething(a:TMyObject1;b:TMyObject2;c:TMyObject3);
begin
   FCriticalSection.Enter;
   try
     if not FList.Contains(a) then
       FList.Add(a);
     ...
   finally
   FCriticalSection.Leave;
   end;
end;

/// elsewhere in the same data module, wherever anybody modifies or checks the state
/// (content) of FList, wrap the method with a critical section like this:
function TMyDataModule.HasItem(a:TMyObject1):Boolean;
begin
   FCriticalSection.Enter;
   try
     result := FList.Contains(a);
   finally
     FCriticalSection.Leave;
   end;
end;

Some starter rules for Delphi multi-threaded programming, in a nutshell are:

*

*Don't do anything that could create a Race Condition.

*Don't forget to use synchronization primitives like Critical Sections, Mutexes, etc, to protect against concurrency issues including Race Conditions, whenever you are accessing any data fields in your class (data module) or ANY globals.  If you use these improperly you add deadlocks to your list of problems.  So this is not a good place to mess up.

*If you must access a VCL component or object in any way, do so indirectly via PostMessage, TThread.Synchronize, or some other thread-safe equivalent way of signaling the main thread that you need something done.

*

*Think about what happens when you're shutting down. Maybe you could check if your data module even exists, since it might have gone away, before you invoke its methods.

A: Short answer: yes
Long answer: The problem with Windows is that all the GUI activity should be done in a single thread. (Well, the above statement can be expanded, amended, enhanced etc. but for our discussion is enough). So, if you are sure that in your TDataModule method there isn't any 'GUI thing' involved (beware, this can be even a ShowMessage call) then go ahead.
UPDATE: Of course, there are techniques to update your GUI from a secondary thread, but this implies some sort of preparation (message passing, Synchronize etc.). Isn't something very hard, just that you cannot 'blindly' call from another thread a method who  changes the GUI.

A: To use our industries favorite answer when asked anything: It depends.
If you have a method on your datamodule that is completely self contained (ie could be a static method), you shouldn't have any problem.
Example
TMyDataModule = class(TDataModule)
public
  function AddOne(const Value: Integer): Integer;
end;

function TMyDataModule.AddOne(const Value: Integer): Integer;
begin
  Result := Value + 1;
end;

If on the other hand, the method uses any global state, you might get into trouble when calling it from multiple threads.
Example
TMyDataModule = class(TDataModule)
private
  FNumber: Integer
public
  function AddOne(const Value: Integer): Integer;
end;

function TMyDataModule.AddOne(const Value: Integer): Integer;
begin
  FNumber := Value
  //***** A context switch here will mess up the result of (at least) one thread.
  Result := FNumber + 1;
end;

Global state should be interpreted very wide. A TQuery, a TTable, refreshing the GUI, using any global variable, ... is all global state and isn't thread safe.

A: Like Lieven writes, it depends.
If you have database components on the datamodule, you have to know if the are thread safe, or to make them threadsafe.
Some database components require a seperate session object per thread.

A: Yes, my question is very vague.
My program is a graphical statistics app, it has to display Gantt chart, by means of TChart, describing the states, alarms or machined orders of one or more Tool Machine.
On the supervisor PC a server (equipped with a TIdTcpServer and some DB components)
is listening to my app on the LAN.
The main-form client allows the final user to choice a range of dates (period) and
the units (machines) to query the server. After that, the user press a button (there are
3 functionalities): a new form (and Datamodule) is created to display the results.
The work of collecting data is completed by a thread because:
1) it can be a long job so it could freeze the GUI;
2) the user can launch more than one form to see various results.
I have a basic Datamodule (with a TIdTcpClient with several function to collect the data),
a basic form (never instantiated, with a lot of characteristics common to all data form, and the definition of the worker thread).
unit dtmPDoxClientU;

  TdtmPDoxClient = class(TDataModule)
    IdTCPClient: TIdTCPClient;
    ...
    function GetData(...): boolean;
    ...
  end;

unit frmChartBaseFormU;

  TfrmChartBaseForm = class(TForm)
    ...
    TheThread: TThreadClient;
    procedure WMThreadComm(var Message: TMessage); message WM_THREADCOMM;
    procedure ListenThreadEvents(var Message: TMessage); virtual;
    procedure ExecuteInThread(AThread: TThreadClient); virtual;
  end;

  TThreadClient = class(TThread)
  private
  public
    Task: integer;
    Module: TfrmChartBaseForm;
    procedure Execute; override;
    property Terminated;
  end;

procedure TfrmChartBaseForm.FormCreate(Sender: TObject);
  ...
  TheThread := TThreadClient.Create(true);
  with TheThread do begin
    Module := self;
    FreeOnTerminate := true;
  end;//with
end;//FormCreate

procedure TfrmChartBaseForm.WMThreadComm(var Message: TMessage);
begin
  ListenThreadEvents(Message);
end;//WMThreadComm

procedure TfrmChartBaseForm.ListenThreadEvents(var Message: TMessage);
begin
// do override in derived classes
end;//ListenThreadEvents

procedure TfrmChartBaseForm.ExecuteInThread(AThread: TThreadClient);
begin
// do override in derived classes
end;//ExecuteInThread

procedure TThreadClient.Execute;
begin
  with Module do begin
    ExecuteInThread(self);
  end;//with
end;//Execute

Furthermore, using VFI, I also have two units:
unit dtmPDoxClientDataOIU;

  TdtmPDoxClientDataOI = class(TdtmPDoxClient)
    cdsClient_IS: TClientDataSet;
    ...
    dsr_I: TDataSource;
    ...
  private
  public
  end;

unit frmPDoxClientDataOIU;

  TfrmPDoxClientDataOI = class(TfrmChartBaseForm)
    ChartOI: TChart;
    ...
    procedure FormCreate(Sender: TObject);
  public
    { Public declarations }
    dtmPDoxClientDataOI: TdtmPDoxClientDataOI;
    procedure ListenThreadEvents(var Message: TMessage); override;
    procedure ExecuteInThread(AThread: TThreadClient); override;
  end;

procedure TfrmPDoxClientDataOI.FormCreate(Sender: TObject);
begin
  inherited;
  dtmPDoxClientDataOI := TdtmPDoxClientDataOI.Create(self);
  TheThread.Task := 1;
  TheThread.Resume;
end;//FormCreate

procedure TfrmPDoxClientDataOI.ListenThreadEvents(var Message: TMessage);
begin
  if (Message.WParam = 1) then begin
    case Message.LParam of
      //GUI tasks, using ClientDataset already compiled and not re-used
    end;//case
  end;//if
end;//ListenThreadEvents

procedure TfrmPDoxClientDataOI.ExecuteInThread(AThread: TThreadClient);
begin
  while not AThread.Terminated and (AThread.Task <> 0) do begin
    case AThread.Task of
      1: begin
        if dtmPDoxClientDataOI.GetData(...) then
          if not AThread.Terminated then begin
            PostMessage(Handle,WM_THREADCOMM,1,1);
            AThread.Task := 2;
          end //if
          else
            AThread.Task := 0;
      end;//1
      ... etc...
    end;//case
  end;//while
end;//ExecuteInThread

So, when the final user presses the button, a new form and its own datamodule and
thread are created; the thread uses its own datamodule by means of ExecuteInThread
function. When data are ready, a PostMessage is sent to the form, which updates
the chart.

A: There is a problem where you work with datamodule in Thread:
If you terminate your thread in OnDestroy event of form and are waiting for it (WaitFor) - you'll have a deadlock.
Main UI thread set lock
procedure TCustomForm.BeforeDestruction;
begin
  GlobalNameSpace.BeginWrite;

and your thread will wait infinitely in it's datamodule destructor with the same
destructor TDataModule.Destroy;
begin
  if not (csDestroying in ComponentState) then GlobalNameSpace.BeginWrite;

So, if you want to wait for your threads when close MainForm, do it in OnClose event or in Project's main file
Or you can destroy it in Synchronize


text:
Q: Appending every second row to the first row in a dataframe I have a dataframe (created from an excel sheet) where every second row needs to be appended to the end of the first row.
For example -
Data in Row 1 = A B C D E ... AK (i.e. the number of columns in the first row is 37)

Data in Row 2 = a b c d e ... l (i.e. the number of columns in the second row is 12)

Data in Row 3 = A B C D E ... AK

Data in Row 4 = a b c d e ... l

etc.
The number of rows is variable (depending on the content of the original spreadsheet) but the number of columns is always the same.
I need row n+1 to be appended to the end of row n resulting in row n having 49 columns of data.
The new rows would look like this -
Row 1 = A B C D E ... AK a b c d e ... l

Row 2 = A B C D E ... AK a b c d e ... l

etc.
The final array will have half the number of rows we started out with.
I think the solution lies in the use of 'reshape' and 'arange', but I can't figure it out.
Thanks


text:
Q: How to get data of json nested objects? I am a newbie learning angularjs. I am trying to access external api to get data from them.
The below image link is the json data that I get after http request from that api:

In js  file I have saved data as $scope.jsondata = data;
I want to create an table which will look like this:

    Date
    age
    avg
    num_payments

     ?
     ?
     ?	  // dont know what to give

because when I tried to access the variable like jsondata.stats.histogram nothing comes up.
If I give jsondata.stats and print them I get following output

1.[{"date":"201311","histogram":[{"ages":"<=18","num_payments":825,"avg":525.24},{"ages":"19-25","num_payments":49628,"avg":243.86},{"ages":"26-35","num_payments":181206,"avg":335.73},{"ages":"36-45","num_payments":208087,"avg":409.1},{"ages":"46-55","num_payments":209074,"avg":387.01},{"ages":"56-65","num_payments":156109,"avg":347.39},{"ages":">=66","num_payments":70881,"avg":400.2},{"ages":"Unknown","num_payments":4133,"avg":658.82}]},{"date":"201312","histogram":[{"ages":"<=18","num_payments":875,"avg":678.74},{"ages":"19-25","num_payments":56716,"avg":243.19},{"ages":"26-35","num_payments":200432,"avg":330.1},{"ages":"36-45","num_payments":227268,"avg":399.74},{"ages":"46-55","num_payments":227818,"avg":385.11},{"ages":"56-65","num_payments":166577,"avg":337.03},{"ages":">=66","num_payments":75534,"avg":373.36},{"ages":"Unknown","num_payments":4075,"avg":609.47}]},{"date":"201401","histogram":[{"ages":"<=18","num_payments":863,"avg":829.89},{"ages":"19-25","num_payments":64139,"avg":215.28},{"ages":"26-35","num_payments":211934,"avg":309.96},{"ages":"36-45","num_payments":236751,"avg":377.17},{"ages":"46-55","num_payments":232784,"avg":409.92},{"ages":"56-65","num_payments":170349,"avg":331.59},{"ages":">=66","num_payments":77767,"avg":386.73},{"ages":"Unknown","num_payments":4084,"avg":674.42}]},{"date":"201402","histogram":[{"ages":"<=18","num_payments":947,"avg":929.1},{"ages":"19-25","num_payments":50168,"avg":227.48},{"ages":"26-35","num_payments":170661,"avg":326.44},{"ages":"36-45","num_payments":192451,"avg":387.63},{"ages":"46-55","num_payments":190980,"avg":396.35},{"ages":"56-65","num_payments":142261,"avg":337.21},{"ages":">=66","num_payments":65938,"avg":397.11},{"ages":"Unknown","num_payments":3685,"avg":629.59}]},{"date":"201403","histogram":[{"ages":"<=18","num_payments":921,"avg":736.56},{"ages":"19-25","num_payments":56525,"avg":216.75},{"ages":"26-35","num_payments":186010,"avg":311.57},{"ages":"36-45","num_payments":204997,"avg":406.57},{"ages":"46-55","num_payments":200943,"avg":404.77},{"ages":"56-65","num_payments":149269,"avg":332.54},{"ages":">=66","num_payments":67746,"avg":403.84},{"ages":"Unknown","num_payments":3786,"avg":644.84}]},{"date":"201404","histogram":[{"ages":"<=18","num_payments":942,"avg":979.4},{"ages":"19-25","num_payments":58174,"avg":230.42},{"ages":"26-35","num_payments":194149,"avg":306.66},{"ages":"36-45","num_payments":223234,"avg":381.75},{"ages":"46-55","num_payments":221479,"avg":389.42},{"ages":"56-65","num_payments":165403,"avg":337.9},{"ages":">=66","num_payments":74967,"avg":392.94},{"ages":"Unknown","num_payments":3848,"avg":548.89}]}] 2.

A: First you have to understand your data structure. It is array of object with date property. For those every dates there are histogram array. So there will be array of array that need to iterate.
I assume you will create one table for every stats date and in every row of that table you want to list histogram data. So we need to iterate date in table level. Later in row level we will iterate histogram array. The structure of the html will be like this below. You can see it live in this link. The example show the data initiated in local. But it will work same with data fetched from server. Furthermore read this documentation to get understand more with angular data iteration.

    Date
    age
    avg
    num_payments

    {{data.date}}
    {{histo.ages}}
    {{histo.avg}}
    ?