text:
Q: mysql get free time set set meeting Ι have a table in MySQL with
     date  starttime    endtime
11/2/2014   10:00:00   10:45:00
11/2/2014   10:45:00   11:15:00
11/2/2014   11:45:00   12:15:00
11/2/2014   12:15:00   13:30:00

I need the sql query to give back to me the time that I can set a new meeting for 30 min

A: $array_time = array();

$query = "SELECT starttime, endtime FROM table";
$result = $mysqli->query($query);

//fetch result
while ($array_time[] = $result->fetch_assoc()) {}

/*
$array_time = Array (
  ...
  1 => array('starttime' => 10:45:00, 'endtime' => 11:15:00)
  2 => array('starttime' => 11:45:00, 'endtime' => 12:15:00)
  ...
)
*/

//array of free time for your meeting
$free_time = array();

foreach($array_time as $i => $row){
  if($i > 0) {
    //if this is not the first time row

    //get this row starttime
    $this_starttime = strtotime($row['starttime']);

    //and the last endtime
    $prev_endtime = strtotime($array_time[$i-1]['endtime']);

    //get the difference
    $diff = $this_starttime - $prev_endtime;

    //if difference is more or equal than 30 minutes
    if($diff >= strtotime('30 minutes')) {
      $free_time[] = array('starttime' => $row['starttime'], $array_time[$i-1]['endtime']);
    }
  }
}

I think you can't do this in MySQL query, so PHP could help you.
Hope it works, I have not tested it out.
But try to save your data by other way, this is not so effective, as you can see.


text:
Q: convert array to array of object Laravel my api receive single array of object from client side like following:
[
         {
         "datetime": "2022-07-19 12:04:03",
         "receiptNumber" : "4010",
         "isRefund": 0,
         "amount" : 1025
          },
]

and whem try to validate request at api side checked success and process to database success my issue happen when try to sent multi object inside array like following :
[
         {
         "datetime": "2022-07-19 12:04:03",
         "receiptNumber" : "4010",
         "isRefund": 0,
         "amount" : 1025
          },

         {
         "datetime": "2022-07-19 12:04:03",
         "receiptNumber" : "4009",
         "isRefund": 0,
         "amount" : 1025
          }

]

when i am try to validate first object inside array using foreach like following :
      $array = $request->all();

      foreach($array as $sdsa){

        $this->validate($sdsa, [
          'datetime' => 'required|date_format:Y-m-d H:i:s',
          'amount' => 'required|numeric',
          'isRefund' => 'required|integer|between:0,1',
          'receiptNumber' => 'required|string',
      ]);

}

in this case api return error :
"message": "Argument 1 passed to App\\Http\\Controllers\\Controller::validate() must be an instance of Illuminate\\Http\\Request, array given,

so that i am asking how can convert this format:
array:4 [
  "datetime" => "2022-07-19 12:04:03"
  "receiptNumber" => "4010"
  "isRefund" => 0
  "amount" => 1025
]

to
{
array:4 [
  "datetime" => "2022-07-19 12:04:03"
  "receiptNumber" => "4010"
  "isRefund" => 0
  "amount" => 1025
]
}

A: You can use 'json_encode()'.
Example;
$myArray = array("datetime" => "2022-07-19 12:04:03", "receiptNumber" => "4010", "isRefund" => 0, "amount" => 1025);

Output;
[
  "datetime" => "2022-07-19 12:04:03",
  "receiptNumber" => "4010",
  "isRefund" => 0,
  "amount" => 1025,
]

Than if you use json_encode like this;
$myArray = json_encode($myArray);

Output;
{
[
  "datetime" => "2022-07-19 12:04:03",
  "receiptNumber" => "4010",
  "isRefund" => 0,
  "amount" => 1025,
]
}

A: You need to use
Validator::make($sdsa, [
      'datetime' => 'required|date_format:Y-m-d H:i:s',
      'amount' => 'required|numeric',
      'isRefund' => 'required|integer|between:0,1',
      'receiptNumber' => 'required|string',
  ])->validate()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python variables passing I want to create a set_range procedures whose goal is to define biggest and smallest number from group of 3. Final step would be minus operation.
I wrote the first two parts but final part is not working. The issue seems to be with passing the variables from one to another...
#biggest number
def biggest(a, y, z):
    Max = a
    if y > Max:
        Max = y
    if z > Max:
        Max = z
        if y > z:
            Max = y
    return Max
#print biggest(10, 4, 7) TEST ONLY

#smallest number
def smallest(a, y, z):
    Small = a
    if y < Small:
        Small = y
    if z < Small:
        Small = z
        if y < z:
            Small = y
    return Small
#print smallest (10, 4, 7) TEST ONLY

#final part of the code, Max - Small operation
def set_range():
  m = Max
  s = Small

print set_range

A: This way you can access all variables from all methods within your code this means, share numbers from biggest() and smallest()
 class getOperationMax(a,y,z):

      def __init__(self,a,y,z):
        self.y = y
        self.a = y
        self.z = y
        self.Max = 0
        self.Small = 0

      #biggest number
      def biggest(self):
          self.Max = self.a
          if self.y > self.Max :
              self.Max = self.y
              self.max = self.y
          if self.z > self.Max:
              self.Max = self.z
              if self.y > self.z:
                  self.Max = self.y

          return self.Max
      #print biggest(10, 4, 7) TEST ONLY

      #smallest number
      def smallest(self):
          self.Small = self.a
          if self.y < self.Small:
              self.Small = self.y
          if self.z < self.Small:
              self.Small = self.z
              if self.y < self.z:
                  self.Small = self.y
          return self.Small
      #print smallest (10, 4, 7) TEST ONLY

    operation = getOperationMax(5,6,7)
    print operation.biggest()
    print operation.smallest()


text:
Q: Phpexcel doesn't update related data in another worksheet I am using PHPExcel 1.8 with 2 worksheets.
Worksheet number 1 is a summary page and worksheet 2 a list of articles with details and amounts.
Worksheet 1 has several references on specifics cells in worksheet 2.
When using insertNewRowBefore methods in worksheet 2 to create the list of articles, the references on related cells in worksheet 1 is not updated.
Cells references are well updated in the same worksheet, but it seems that a limitation exists if cells are referenced in other worksheet.
Documentation says that all possible related data are updated.
Is it a bug? A limitation? Or is there a way to do it?

A: PHPExcel confirms the limitation
https://github.com/PHPOffice/PHPExcel/issues/1099


text:
Q: Search page with MVC + Linq + EF So, I want to implement a page that searches the database for records. The url of the action should be something like "~/Mail/List/{PropertyName}/{PropertyValue}.
Property name and value are the corresponding entity property name to filter by and the value is the property value to match. The thing is that the entity contains properties of many types. Int, string, date.. etc.
The question is, how do I implement a dynamic search page or something like that to filter my queries?
Thanks!

A: All LINQ operators expects lambdas to be passed in. So when you want to do filtering like Where(x => x.[PropertyName] == [PropertyValue]), you need to be able to construct the corresponding lambda expression. Normally, when values are known at compile time, there's no problem, you'll just construct the lambda.
When you don't know the values at compile time, you have to construct expression tree (that is essentially what lambda expression is made of) manually. This can be a bit complicated, but there are libraries to help you, like Dynamic LINQ (here is another good tutorial with EF). You can then specify your Where condition as a string and the library at runtime will translate it into expression tree or throw an exception if it is wrong.
So, in your example, using Dynamic LINQ, you can do your query like db.Mails.Where(PropertyName + " == @0", PropertyValue);


text:
Q: IIS SSL with Multiple Sites and 1 IP I have these sites:
app.example.com
api.example.com
staff.example.com
www.example.com / example.com
I used LetsEncrypt to generate free SSLs for each of the sites. Things seem to be fine except it seems that only one SSL cert is being served for all of the sites! I even removed and manually readded the SSL bindings to each of the sites and still had the same problem. I ended up removing all of the SSL certs except my API one and removed all of the SSL bindings except for the API Web Site, and bizarrely, I can still load the other sites as HTTPS even though I removed the SSL bindings for those Web Sites (the remaining SSL cert is of course showing for all of the sites still)! Wth? I thought you need the 443/SSL Bindings in order to even browse that site via https! I can confirm that these are all individual Web Sites, not Virtual Apps inside of a single Web Site. What am I missing? How can I get IIS to serv up the right cert for the right Web Site? This is a Azure VM running Win Server 2012 R2.

A: This can be done with Server Name Indication
From the IIS management interface, you can select each web site, and Edit Bindings....
In the pop-up window, select the https site and the Edit... button. Fill in the Host name: field with the specific website host name, check the Require Server Name Indication and select the specific ceritificate to use for that site in the SSL certificate dropdown.
This will allow you to host multiple secure sites on the same server. It is an improvement introduced in IIS v.8

A: You need to get a certificate that has all those names as subject names or a wildcard certificate. So, single certificate will be used for all of them. After that, you can configure each website with that certificate and SNI.


text:
Q: How the Stream.filter() method works? I know how the lambda expresion works and I know it is an argument for .filter() that establish the criteria to filter with. But I don't get  how .filter() uses the argument, in this case a lambda expression, because .filter() does't have an implementation or at least require one at compile time. I search for this unknown implementation in the Oracle's site but there are just a few words explaning how it works and no code at all.
Is that implemetation hidden or is created automatically by the java compiler?
Does an aggregate operation need one?
double average = roster
  .stream()
  .filter(p -> p.getGender() == Person.Sex.MALE)
  .mapToInt(Person::getAge)
  .average()
  .getAsDouble();

roster is a List<Person> instance of ArrayList<Person>
Person is a simple class that represents a person

A: The lambda object is created automatically by the compiler.
Any "functional" interface (that is an interface with just 1 function) can be the target for one. The equivalent non-lambda code would be:
double average = roster
.stream()
.filter(new Predicate<Person>(){
          public boolean test(Person p){
              return p.getGender() == Person.Sex.MALE;
           }
      })
.mapToInt(Person::getAge)
.average()
.getAsDouble();

And it could have been implemented this way by the compiler but they were concerned with efficiency and wanted people to be able to reference methods directly. So instead they translate the lambda to a private method which may or may not be static (depending on whether this is captured) and use a meta factory that creates the actual lambda object which then forwards to the actual code in the private method.
For more information see the following page.

A: The Collection interface now has a default method that implements the stream() method that returns the stream. Default methods are new to Java 8 and allow for interfaces to implement methods in order to evolve the API. So this implementation of the stream() method on the Collection must be constructing an object that implements the Stream interface and returns it.
Internally, the Collection interface method stream() forwards a call to the StreamSupport class that is documented. The SteamSupport class in turn constructs an undocumented class called ReferencePipeline that you can find in the java source code in the java 8 JDK.
So, apparently it is the intention of the API designer that if you want to do some custom stream stuff you would go no further than the StreamSupport class.


text:
Q: What is a vim regex for "abcd", where "bc" is optional? I want to search for occurrences of ad and abcd where the bc is optional.  How can I do that?  i.e.,
+-------+----------+
| ad    | MATCH    |
| abcd  | MATCH    |
| abd   | NO match |
| abbd  | NO match |
| abced | NO match |
| abcbcd| NO match |
+-------+----------+

A: /ad\|abcd
[\| is logical OR (alternation)]

A: Solutions:
option 1: ad\|abcd
option 2: a\(bc\)\=d
option 3: a\(bc\)\?d
option 4: \va%[(bc)]d
option 5: a\%[\(bc\)]d
Close but not quite:
a\(bc\)\{-\}d
(zero or more; matches abcbcd which is not desired)
+--------+--------------------------+---------------+
| syntax | description              | documentation |
+--------+--------------------------+---------------|
| \|     | logical OR (alternation) | :help /\|     |
| \(bc\) | treat `bc` as a group    | :help /atom   |
| \=     | zero or one occurrences  | :help \=      |
| \?     | zero or one occurrences  | :help \?      |
| \{-\}  | zero or more occurrences |               |
| \%[]   | make the match optional  | :help \%[]    |
| \v     | "very magic": omit \'s   | :help \v      |
+--------+--------------------------+---------------+

A: Here's another option where "bc" is optional.
\va%[(bc)]d
Without the \v ("very magic"):
a\%[\(bc\)]d
Explanation:
\%[] makes a match optional.
\(bc\) groups "bc".
\v (very magic) at the beginning allows you to omit the backslash \.


text:
Q: Databinding on code behind works the second time I am having an issue with the databinding on code behind. Unfortunately, doing the databinding on xaml is not possible since the binding source changes between different objects
The thing is, the first time I execute this line
hexview.SetBinding(HexViewer.RawStringProperty, new Binding() { Path = new PropertyPath("Rawstring"), Source = object1.ClassProperty1, Mode = BindingMode.TwoWay });

it does not bind, but the second time it does.
If I add this code to the click event of a button and then I change the value with the UI, the changes are not reflected.
If i click the button two times, everything works.
On the output window I don't see any error. Any idea why this weird behaviour?
Any direction point will be really appreciated.
Thank you
Fernando


text:
Q: Add folder to all URLs in an ASP.net MVC 5 site I have an MVC 5 site with this structure:
example.com
example.com/area1 (index for whole section)
example.com/area2/item5 (specific item for section)

For SEO reasons I'd like to change every URL to this:
example.com/keyword (redirected from example.com)
example.com/keyword/area1
example.com/keyword/area2/item5

The keyword is fixed and always the same, though at some point in the future there may be a site with the same structure but different content with a different keyword in. That is probably at least a few months off though.
What is the quickest / easiest way to implement the above. Being able to get the name of keyword would be an advantage later though isn't essential right now.
I could use attribute routing, though I'd have to update A LOT of ActionMethods to do this - and most currently don't even use attribute routing.
thx.
Update
I've tried adding the below to RouteConfig.cs, but none of the Url's work for some reason:
routes.MapRoute(
    name: "Default",
    url: "keyword/{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

A: public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    string  keyword = "keyword";
    // keyword route - it will be used as a route of the first priority
    routes.MapRoute(
        name: "Defaultkeyword",
        url: "{keyword}/{controller}/{action}/{id}",
        defaults: new
        {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional,
            keyword = keyword
        });

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

also you need to add this Defaultkeyword route with few changes into your Area1AreaRegistration.cs file
public override void RegisterArea(AreaRegistrationContext context)
 {
     context.MapRoute(
            "Area1_defaultKeyword",
            "{Keyword}/Area1/{controller}/{action}/{id}",
            new { Keyword = "Keyword", controller = "HomeArea1", action = "Index", id = UrlParameter.Optional }
            );

 context.MapRoute(
            "Area1_default",
            "Area1/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
           );
 }


text:
Q: Quitar texto de un select con JQuery ¿me pueden ayudar con una función que quite los textos de dos combos?
Los combos son los siguientes:

EL problema esta en que al eliminar la selección del combo País los otros combos (Estado y Municipio), deben limpiarse, es decir ya no debe mostrar Lima ni San Isidro. Ya lo intente y lo único que me sale bien es detectar que País ya se encuentra vacío. No se que atributos debo usar para que no me muestre los textos. Y este es el código:
jQuery(document).ready(function(){

    $('#tblempleados-pais').on('change', function(){

        if($('#tblempleados-pais').val() == '' || $('#tblempleados-pais').val() == null){

            alert('entra');
            $('#tblempleados-estado').val('');
            $('#tblempleados-municipio').val('');

        }

    });

});

A: Gracias a todos y tenia razón Camilo Vasquez era por la librería la respuesta era simple de igual forma pero nunca pensé que chocaría con eso. Es reemplazar esto:
$('#tblempleados-estado').val('');
$('#tblempleados-municipio').val('');

Por esto:
$("#tblempleados-estado").select2("val", "");
$("#tblempleados-municipio").select2("val", "");

A: Sin modificar tu JavaScript, agrega una opción en blanco a cada select. Ejemplo:

jQuery(document).ready(function(){

    $('#tblempleados-pais').on('change', function(){

        if($('#tblempleados-pais').val() == '' || $('#tblempleados-pais').val() == null){

            alert('entra');
            $('#tblempleados-estado').val('');
            $('#tblempleados-municipio').val('');

        }

    });

});

País <select type="text" id="tblempleados-pais">

<option></option>
<option selected="selected" value="Peru">Perú</option>

</select>

Estado <select type="text" id="tblempleados-estado">
<option></option>
<option selected="selected" value="Lima">Lima</option>
</select>

Municipio <select type="text" id="tblempleados-municipio">
<option></option>
<option selected="selected" value="San Isidro">San Isidro</option>
</select>


text:
Q: How add view over TextureView i need to add View over my TextureView which play video in it
i used VideoView before and it was totally fine but i had problem with animation so i changed it to TextureView and now i can't put any View over it!
seems that Textureview will cover over all views
this is my xml layout :
  <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/frmview"
    >

    <com.my.app.TextureVideoView
        android:id="@+id/vv_play"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:alpha="0.0" />

    <ImageView
        android:id="@+id/iv_play"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srcCompat="@drawable/app_ic" />
</FrameLayout>

How can i put a View over TextureView which is playing video?

A: finally i had to add it programmically to my FrameLayout after initializing TextureView and playing video!
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    mPreview = (TextureView) findViewById(R.id.vv_play);
    mPreview.setSurfaceTextureListener(this);
    FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frmview);

    ImageView img = new ImageView(this);
    img.setImageResource(R.drawable.app_ic);
    frameLayout.addView(img);
}

A: Perhaps you can try this api of TextureView:
TextureView.setOpaque(false);

A: TextureView that constantly updates its content (e.g. playing video) will always overdraw any View content that is put on the top of it (e.g. TextureView and some other View puted inside FrameLayout container).
The best solution I found to handle that is to show the top View inside another Window that sits on top of Window that contains TextureView, e.g. PopupWindow can be used for that.


text:
Q: How do I play an FLV file in Haxe? It is very difficult to find good resources for Haxe information so I am hoping someone out there can help me. I have an FLV movie in the same directory as the SWF I am generating. I cannot get the FLV to play. I can get this working in AS but I need to know what I am doing wrong in my Haxe code.
Hope someone can help.
var mc:MovieClip = Lib._root;

var connection:NetConnection = new NetConnection();
connection.connect(null);
var stream:NetStream = new NetStream(connection);

mc.attachVideo(stream);
trace(mc.flash.Video);
stream.play("default.flv");

A: Here is a Google Code project that demos a nice flash media server. It plays and even records videos. http://code.google.com/p/haxevideo/

A: There's nothing inherently different from Haxe and AS when it comes to play video as you would be using AS libraries. To which player are you compiling to? Because if you are compiling to player >= 9 you are missing a few bits.
You can check out my example of AS3 player here (scroll down to createVideo()) to find out exactly what (create the Video object, attach to the display list, etc).
I'm also guessing that you are not getting any compiler errors, right?
Juan

A: What player version do you target? For 10 the stage is flash.Lib.current.
Do haxe compiler says something about errors?


text:
Q: unreachable statement  Вот есть сам код: (это игра крестики нолики)
public class Main {

    public static char[][] map;
    public static final int SIZE = 5;
    public static final int DOTS_TO_WIN = 4;
    public static final char DOT_EMPTY = '•';
    public static final char DOT_X = 'X';
    public static final char DOT_O = 'O';
    public static Scanner vvod = new Scanner(System.in);

    public static void newMap() {
        map = new char[SIZE][SIZE];
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                map[i][j] = DOT_EMPTY;
            }
        }
    }

    public static void printMap() {
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                System.out.print(map[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void human() {
        int x, y;
        do {
            System.out.println("Введите координаты точки (х у)");
            x = vvod.nextShort() - 1;
            y = vvod.nextShort() - 1;
        } while (!freefield(x, y));
        map[x][y] = DOT_X;
    }

    public static void comp() {
        int x, y;
        do {
            x = (int) (Math.random() * 6) - 1;
            y = (int) (Math.random() * 6) - 1;
        } while (!freefield(x, y));
        System.out.println("ход компьютера: x-" + (x + 1) + " у-" + (y + 1));
        map[x][y] = DOT_O;
    }

    public static boolean freefield(int x, int y) {
        if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) {
            return false;
        }
        return map[y][x] == DOT_EMPTY;
    }

    public static boolean fullmap() {
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                if (map[i][j] == DOT_EMPTY) return false;
            }
        }
        return true;
    }

    public static boolean proverka (char symb) {
        int x_win = 0, y_win = 0, col=0, row = 0, stop_1, stop_2;
        do {
            for (col = 0; col < 4; col++) {
                if (map[col][row] == symb) x_win++;
                else x_win = 0;
            }
            row++;
            if (x_win == 4) break; else x_win = 0;
        } while (row!=5) ;
        col = 0;
        do {
            for (row = 0; row < 4; row++) {
                if (map[row][col] == symb) y_win++;
                else y_win = 0;
            }
            col++;
            if (y_win == 4) break; else y_win = 0;
        } while (col!=5) ;
        if (x_win == 4 || y_win == 4) return true; else return false;
    }

    public static void main(String[] args) {
        newMap();
        printMap();
        while (true) {
            human();
            printMap();
            if (proverka(DOT_X));{
                System.out.println("Победа человека");
                break;
            }
            if (fullmap()){
                System.out.println("Ничья");
                break;
            }
            comp();
            printMap();
            if (proverka(DOT_O));{
                System.out.println("Победа компьютера");
               // break;
            }
            if (fullmap()){
                System.out.println("Ничья");
                break;
            }
        }
        System.out.println("Game over");
    }

В методе Main в цикле While есть вызывается класс proverka. В этом классе есть break, который выводит нас из цикла, если возвращается true. Если false цикл продолжается дальше. Однако:
if (proverka(DOT_X));{
            System.out.println("Победа человека");
            break;
        }
        if (fullmap()){
            System.out.println("Ничья");
            break;
        }

Второй IF уже не работает после break и программа говорит, что этот IF -
 unreachable statement. Уже битый час не могу разобраться почему так, может тут помогут ☺☻

A: Проблема очевидно тут:
if (proverka(DOT_X)); {         if (proverka(DOT_O)); {
                    ^---         и                  ^----

A: Во-первых, нужно убрать точку с запятой после условия в if - если условие будет выполняться, ничего не будет происходить. А тот блок, который в логике твоего кода должен выполняться при этом условии - будет выполняться всегда , думай об этом так - если бы в твоем коде вообще не было бы  этой строки:
if (proverka(DOT_X));

Таким образом, у тебя программа всегда вылетает из цикла (потому что break в этом блоке находится) и даже не доходит до второго if


text:
Q: Windows C++ crypto API: how to disable pin code UI for smart card I have the following C++ code (based on Microsoft API examples), it uses message signing and encryption API to produce PKCS#7 message.
There is a hardware token with certificate inserted (Yubikey) which requires a PIN code for the signing operation.
I want to disable the standard Windows pin popup and provide my own, so there is a call to CryptSetProvParam with a pin code.
The issue is that this call has no effect: I am still prompted with pin code.
If I add CertSetCertificateContextProperty call afterwards and set the key provider handle then nothing works anymore, for example CryptMsgCalculateEncodedLength returns 0x80090027.
If I comment out CertSetCertificateContextProperty then all operations are working but the pin code popup is still shown.
#pragma comment(lib, "crypt32.lib")

#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
void MyHandleError(char* s);

void main(void)
{
    //-------------------------------------------------------------------
    // Copyright (C) Microsoft.  All rights reserved.
    // Declare and initialize variables.

    BYTE* pbContent = (BYTE*)"Security is our only business.";
    // a byte pointer
    DWORD cbContent = strlen((char*)pbContent) + 1;
    // the size of the message
    HCERTSTORE hStoreHandle;
    HCRYPTPROV hCryptProv;
    PCCERT_CONTEXT pSignerCert;         // signer's certificate
    PCCERT_CONTEXT pRecipCert;          // receiver's certificate
    LPWSTR pswzRecipientName = L"myrecipient";
    LPWSTR pswzCertSubject = L"mysubject";
    PCERT_INFO RecipCertArray[1];
    DWORD ContentEncryptAlgSize;
    CRYPT_ALGORITHM_IDENTIFIER ContentEncryptAlgorithm;
    CMSG_ENVELOPED_ENCODE_INFO EnvelopedEncodeInfo;
    DWORD cbEncodedBlob;
    BYTE* pbEncodedBlob;
    DWORD cbSignedBlob;
    BYTE* pbSignedBlob;
    HCRYPTMSG hMsg;
    DWORD HashAlgSize;
    CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
    CMSG_SIGNER_ENCODE_INFO SignerEncodeInfo;
    CERT_BLOB SignerCertBlob;
    CERT_BLOB SignerCertBlobArray[1];
    CMSG_SIGNER_ENCODE_INFO SignerEncodeInfoArray[1];
    CMSG_SIGNED_ENCODE_INFO SignedMsgEncodeInfo;
    DWORD dwKeySpec = 0;
    HCRYPTPROV rsaCryptProv = NULL;

    //-------------------------------------------------------------------
    // Begin processing. Display the original message.

    printf("The original message => %s\n", pbContent);

    //-------------------------------------------------------------------
    // Acquire a cryptographic provider.

    if (CryptAcquireContext(
        &hCryptProv,      // address for handle to be returned
        NULL,             // use the current user's logon name
        NULL,             // use the default provider
        PROV_RSA_FULL,    // provider type
        0))               // zero allows access to private keys
    {
        printf("Context CSP acquired. \n");
    }
    else
    {
        if (GetLastError() == NTE_BAD_KEYSET)
        {
            printf("A Usable private key was not found \n");
            printf("in the default key container. Either a \n");
            printf("private key must be generated in that container \n");
            printf("or CryptAquireCertificatePrivateKey can be used \n");
            printf("to gain access to the needed private key.");
        }
        MyHandleError("CryptAcquireContext failed.");
    }

    //-------------------------------------------------------------------
    // Open the My system certificate store.

    if (hStoreHandle = CertOpenStore(
        CERT_STORE_PROV_SYSTEM,
        0,
        NULL,
        CERT_SYSTEM_STORE_CURRENT_USER,
        L"MY"))
    {
        printf("The MY system store is open. \n");
    }
    else
    {
        MyHandleError("Error getting store handle.");
    }
    //-------------------------------------------------------------------
    // Get the signer's certificate. This certificate must be in the
    // My store, and its private key must be available.

    if (pSignerCert = CertFindCertificateInStore(
        hStoreHandle,
        MY_ENCODING_TYPE,
        0,
        CERT_FIND_SUBJECT_STR,
        pswzCertSubject,
        NULL))
    {
        printf("Found certificate for %S.\n", pswzCertSubject);
    }
    else
    {
        MyHandleError("Signer certificate not found.");
    }

    if (!CryptAcquireCertificatePrivateKey(pSignerCert, CRYPT_ACQUIRE_CACHE_FLAG | CRYPT_ACQUIRE_SILENT_FLAG, NULL, &rsaCryptProv, &dwKeySpec, NULL))
    {
        MyHandleError("Cannot acquire private key.");
    }

   // does not seem to have any effect
    if (!CryptSetProvParam(rsaCryptProv, dwKeySpec == AT_KEYEXCHANGE ? PP_KEYEXCHANGE_PIN : PP_SIGNATURE_PIN, (LPBYTE)"123456", 0))
    {
        MyHandleError("Cannot set key pin.");
    }

   // causes all subsequent operations to fail
    if (!CertSetCertificateContextProperty(pSignerCert, CERT_KEY_PROV_HANDLE_PROP_ID, 0, (const void*)rsaCryptProv))
    {
        MyHandleError("Cannot set cert property.");
    }

    //-------------------------------------------------------------------
    // Initialize the algorithm identifier structure.

    HashAlgSize = sizeof(HashAlgorithm);
    memset(&HashAlgorithm, 0, HashAlgSize);    // initialize to zero
    HashAlgorithm.pszObjId = szOID_RSA_SHA256RSA;    // initialize the
                                               // necessary member
    //-------------------------------------------------------------------
    // Initialize the CMSG_SIGNER_ENCODE_INFO structure.

    memset(&SignerEncodeInfo, 0, sizeof(CMSG_SIGNER_ENCODE_INFO));
    SignerEncodeInfo.cbSize = sizeof(CMSG_SIGNER_ENCODE_INFO);
    SignerEncodeInfo.pCertInfo = pSignerCert->pCertInfo;
    SignerEncodeInfo.hCryptProv = rsaCryptProv;
    SignerEncodeInfo.dwKeySpec = dwKeySpec;
    SignerEncodeInfo.HashAlgorithm = HashAlgorithm;
    SignerEncodeInfo.pvHashAuxInfo = NULL;

    //-------------------------------------------------------------------
    // Create an array of one.
    // Note: The current program is set up for only a single signer.

    SignerEncodeInfoArray[0] = SignerEncodeInfo;

    //-------------------------------------------------------------------
    // Initialize the CMSG_SIGNED_ENCODE_INFO structure.

    SignerCertBlob.cbData = pSignerCert->cbCertEncoded;
    SignerCertBlob.pbData = pSignerCert->pbCertEncoded;

    //-------------------------------------------------------------------
    // Initialize the array of one CertBlob.

    SignerCertBlobArray[0] = SignerCertBlob;
    memset(&SignedMsgEncodeInfo, 0, sizeof(CMSG_SIGNED_ENCODE_INFO));
    SignedMsgEncodeInfo.cbSize = sizeof(CMSG_SIGNED_ENCODE_INFO);
    SignedMsgEncodeInfo.cSigners = 1;
    SignedMsgEncodeInfo.rgSigners = SignerEncodeInfoArray;
    SignedMsgEncodeInfo.cCertEncoded = 1;
    SignedMsgEncodeInfo.rgCertEncoded = SignerCertBlobArray;
    SignedMsgEncodeInfo.rgCrlEncoded = NULL;

    //-------------------------------------------------------------------
    // Get the size of the encoded, signed message BLOB.

    if (cbSignedBlob = CryptMsgCalculateEncodedLength(
        MY_ENCODING_TYPE,       // message encoding type
        0,                      // flags
        CMSG_SIGNED,            // message type
        &SignedMsgEncodeInfo,   // pointer to structure
        NULL,                   // inner content OID
        cbContent))             // size of content
    {
        printf("%d, the length of data calculated. \n", cbSignedBlob);
    }
    else
    {
        if (GetLastError() == NTE_BAD_KEYSET)
        {
            printf("A Usable private key was not found \n");
            printf("in the default key container. Either a \n");
            printf("private key must be generated in that container \n");
            printf("or CryptAquireCertificatePRivateKey can be used \n");
            printf("to gain access to the needed private key.");
        }
        MyHandleError("Getting cbSignedBlob length failed.");
    }
    //-------------------------------------------------------------------
    // Allocate memory for the encoded BLOB.

    if (pbSignedBlob = (BYTE*)malloc(cbSignedBlob))
    {
        printf("Memory has been allocated for the signed message. \n");
    }
    else
    {
        MyHandleError("Memory allocation failed.");
    }
    //-------------------------------------------------------------------
    // Open a message to encode.

    if (hMsg = CryptMsgOpenToEncode(
        MY_ENCODING_TYPE,        // encoding type
        0,                       // flags
        CMSG_SIGNED,             // message type
        &SignedMsgEncodeInfo,    // pointer to structure
        NULL,                    // inner content OID
        NULL))                   // stream information (not used)
    {
        printf("The message to be encoded has been opened. \n");
    }
    else
    {
        MyHandleError("OpenToEncode failed.");
    }
    //-------------------------------------------------------------------
    // Update the message with the data.

    if (CryptMsgUpdate(
        hMsg,         // handle to the message
        pbContent,    // pointer to the content
        cbContent,    // size of the content
        TRUE))        // last call
    {
        printf("Content has been added to the encoded message. \n");
    }
    else
    {
        MyHandleError("MsgUpdate failed.");
    }
    //-------------------------------------------------------------------
    // Get the resulting message.

    if (CryptMsgGetParam(
        hMsg,                      // handle to the message
        CMSG_CONTENT_PARAM,        // parameter type
        0,                         // index
        pbSignedBlob,              // pointer to the BLOB
        &cbSignedBlob))            // size of the BLOB
    {
        printf("Message encoded successfully. \n");
        FILE* fp = fopen("signed.p7m", "wb");
        fwrite(pbSignedBlob, cbSignedBlob, 1, fp);
        fclose(fp);
    }
    else
    {
        MyHandleError("MsgGetParam failed.");
    }
    //-------------------------------------------------------------------
    // pbSignedBlob now points to the encoded, signed content.

    //-------------------------------------------------------------------
    // Get a pointer to the recipient certificate.
    // For this program, the recipient's certificate must also be in the
    // My store. At this point, only the recipient's public key is needed.
    // To open the enveloped message, however, the recipient's
    // private key must also be available.

    if (pRecipCert = CertFindCertificateInStore(
        hStoreHandle,
        MY_ENCODING_TYPE,            // use X509_ASN_ENCODING
        0,                           // no dwFlags needed
        CERT_FIND_SUBJECT_STR,       // find a certificate with a
                                     // subject that matches the
                                     // string in the next parameter
        pswzRecipientName,           // the Unicode string to be found
                                     // in a certificate's subject
        NULL))                       // NULL for the first call to the
                                     // function
                                     // in all subsequent
                                     // calls, it is the last pointer
                                     // returned by the function
    {
        printf("Certificate for %S found. \n", pswzRecipientName);
    }
    else
    {
        MyHandleError("Could not find the countersigner's "
            "certificate.");
    }
    //-------------------------------------------------------------------
    // Initialize the first element of the array of CERT_INFOs.
    // In this example, there is only a single recipient.

    RecipCertArray[0] = pRecipCert->pCertInfo;

    //-------------------------------------------------------------------
    // Initialize the symmetric-encryption algorithm identifier
    // structure.

    ContentEncryptAlgSize = sizeof(ContentEncryptAlgorithm);
    memset(&ContentEncryptAlgorithm,
        0,
        ContentEncryptAlgSize);               // initialize to zero

 //-------------------------------------------------------------------
 // Initialize the necessary members. This particular OID does not
 // need any parameters. Some OIDs, however, will require that
 // the other members be initialized.

    ContentEncryptAlgorithm.pszObjId = szOID_RSA_DES_EDE3_CBC;

    //-------------------------------------------------------------------
    // Initialize the CMSG_ENVELOPED_ENCODE_INFO structure.

    memset(&EnvelopedEncodeInfo,
        0,
        sizeof(CMSG_ENVELOPED_ENCODE_INFO));
    EnvelopedEncodeInfo.cbSize = sizeof(CMSG_ENVELOPED_ENCODE_INFO);
    EnvelopedEncodeInfo.hCryptProv = hCryptProv;
    EnvelopedEncodeInfo.ContentEncryptionAlgorithm =
        ContentEncryptAlgorithm;
    EnvelopedEncodeInfo.pvEncryptionAuxInfo = NULL;
    EnvelopedEncodeInfo.cRecipients = 1;
    EnvelopedEncodeInfo.rgpRecipients = RecipCertArray;

    //-------------------------------------------------------------------
    // Get the size of the encoded message BLOB.

    if (cbEncodedBlob = CryptMsgCalculateEncodedLength(
        MY_ENCODING_TYPE,        // message encoding type
        0,                       // flags
        CMSG_ENVELOPED,          // message type
        &EnvelopedEncodeInfo,    // pointer to structure
        NULL,    // inner content OID
        cbSignedBlob))           // size of content
    {
        printf("Length of the encoded BLOB will be %d.\n", cbEncodedBlob);
    }
    else
    {
        MyHandleError("Getting enveloped cbEncodedBlob length failed.");
    }
    //--------------------------------------------------------------------
    // Allocate memory for the encoded BLOB.

    if (pbEncodedBlob = (BYTE*)malloc(cbEncodedBlob))
    {
        printf("Memory has been allocated for the BLOB. \n");
    }
    else
    {
        MyHandleError("Enveloped malloc operation failed.");
    }
    //-------------------------------------------------------------------
    // Open a message to encode.

    if (hMsg = CryptMsgOpenToEncode(
        MY_ENCODING_TYPE,        // encoding type
        0,                       // flags
        CMSG_ENVELOPED,          // message type
        &EnvelopedEncodeInfo,    // pointer to structure
        NULL,    // inner content OID
        NULL))                   // stream information (not used)
    {
        printf("The message to encode is open. \n");
    }
    else
    {
        MyHandleError("Enveloped OpenToEncode failed.");
    }
    //-------------------------------------------------------------------
    // Update the message with the data.

    if (CryptMsgUpdate(
        hMsg,              // handle to the message
        pbSignedBlob,      // pointer to the signed data BLOB
        cbSignedBlob,      // size of the data BLOB
        TRUE))             // last call
    {
        printf("The signed BLOB has been added to the message. \n");
    }
    else
    {
        MyHandleError("Enveloped MsgUpdate failed.");
    }
    //-------------------------------------------------------------------
    // Get the resulting message.

    if (CryptMsgGetParam(
        hMsg,                  // handle to the message
        CMSG_CONTENT_PARAM,    // parameter type
        0,                     // index
        pbEncodedBlob,         // pointer to the enveloped,
                               // signed data BLOB
        &cbEncodedBlob))       // size of the BLOB
    {
        printf("Enveloped message encoded successfully. \n");
        FILE* fp = fopen("encoded.p7m", "wb");
        fwrite(pbEncodedBlob, cbEncodedBlob, 1, fp);
        fclose(fp);
    }
    else
    {
        MyHandleError("Enveloped MsgGetParam failed.");
    }
    //-------------------------------------------------------------------
    // Clean up.

    CertFreeCertificateContext(pRecipCert);
    if (CertCloseStore(
        hStoreHandle,
        CERT_CLOSE_STORE_CHECK_FLAG))
    {
        printf("The certificate store closed without a certificate "
            "left open. \n");
    }
    else
    {
        printf("The store closed but a certificate was still open. \n");
    }
    if (hMsg)
        CryptMsgClose(hMsg);
    if (hCryptProv)
        CryptReleaseContext(hCryptProv, 0);
} // end main

//-------------------------------------------------------------------
// This example uses the function MyHandleError, a simple error
// handling function to print an error message and exit
// the program.
// For most applications, replace this function with one
// that does more extensive error reporting.

void MyHandleError(char* s)
{
    fprintf(stderr, "An error occurred in running the program. \n");
    fprintf(stderr, "%s\n", s);
    fprintf(stderr, "Error number %x.\n", GetLastError());
    fprintf(stderr, "Program terminating. \n");
    exit(1);
} // end MyHandleError

A: Found an answer and posting it here in case anyone needs it. The trick is to use CNG API instead of legacy crypto API:
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>

#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)

void MyHandleError(const char* s);

int main()
{
    BYTE* pbContent = (BYTE*)"Security is our only business.";
    DWORD cbContent = strlen((char*)pbContent) + 1;

    LPCWSTR pswzRecipientName = L"recipient";
    LPCWSTR pswzCertSubject = L"signer";

    HCERTSTORE hStoreHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER, L"my");

    if (hStoreHandle != NULL)
    {
        printf("The MY system store is open. \n");
    }
    else
    {
        MyHandleError("Error getting store handle.");
    }

    PCCERT_CONTEXT pSignerCert = CertFindCertificateInStore(hStoreHandle, MY_ENCODING_TYPE, 0, CERT_FIND_SUBJECT_STR, pswzCertSubject, NULL);

    if (pSignerCert != NULL)
    {
        printf("Found certificate for %S.\n", pswzCertSubject);
    }
    else
    {
        MyHandleError("Signer certificate not found.");
    }

    PCCERT_CONTEXT pRecipCert = CertFindCertificateInStore(hStoreHandle, MY_ENCODING_TYPE, 0, CERT_FIND_SUBJECT_STR, pswzRecipientName, NULL);

    if (pRecipCert != NULL)
    {
        printf("Certificate for %S found. \n", pswzRecipientName);
    }
    else
    {
        MyHandleError("Could not find the countersigner's "
            "certificate.");
    }

    NCRYPT_HANDLE rsaKey;
    DWORD dwKeySpec = 0;
    if (!CryptAcquireCertificatePrivateKey(pSignerCert, CRYPT_ACQUIRE_CACHE_FLAG | CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG, NULL, &rsaKey, &dwKeySpec, NULL))
    {
        MyHandleError("Cannot acquire private key.");
    }

    if (NCryptSetProperty(rsaKey, NCRYPT_PIN_PROPERTY, (BYTE*)L"123456", 6, 0) != ERROR_SUCCESS)
    {
        MyHandleError("NCryptSetProperty failed.");
    }

    CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
    memset(&HashAlgorithm, 0, sizeof(HashAlgorithm));
    HashAlgorithm.pszObjId = szOID_RSA_SHA256RSA;

    CRYPT_SIGN_MESSAGE_PARA SignParam;
    memset(&SignParam, 0, sizeof(SignParam));
    SignParam.cbSize = sizeof(SignParam);
    SignParam.dwMsgEncodingType = MY_ENCODING_TYPE;
    SignParam.pSigningCert = pSignerCert;
    SignParam.cMsgCert = 1;
    SignParam.rgpMsgCert = &pSignerCert;
    SignParam.HashAlgorithm = HashAlgorithm;
    SignParam.dwFlags = CRYPT_MESSAGE_SILENT_KEYSET_FLAG;

    CRYPT_ALGORITHM_IDENTIFIER CryptAlg;
    memset(&CryptAlg, 0, sizeof(CryptAlg));
    CryptAlg.pszObjId = szOID_RSA_DES_EDE3_CBC;

    CRYPT_ENCRYPT_MESSAGE_PARA EncryptParam;
    memset(&EncryptParam, 0, sizeof(EncryptParam));
    EncryptParam.cbSize = sizeof(EncryptParam);
    EncryptParam.dwMsgEncodingType = MY_ENCODING_TYPE;
    EncryptParam.ContentEncryptionAlgorithm = CryptAlg;

    DWORD cbEncodedBlob = 0;
    if (!CryptSignAndEncryptMessage(&SignParam, &EncryptParam, 1, &pRecipCert, pbContent, cbContent, NULL, &cbEncodedBlob))
    {
        MyHandleError("CryptSignAndEncrypteMessage failed.");
    }

    BYTE* pbEncodedBlob = (BYTE*)malloc(cbEncodedBlob);
    if (!CryptSignAndEncryptMessage(&SignParam, &EncryptParam, 1, &pRecipCert, pbContent, cbContent, pbEncodedBlob, &cbEncodedBlob))
    {
        MyHandleError("CryptSignAndEncrypteMessage failed.");
    }
    else
    {
        printf("Message signed and encrypted successfully. \n");
        FILE* fp = fopen("signed-encrypted.p7m", "wb");
        fwrite(pbEncodedBlob, cbEncodedBlob, 1, fp);
        fclose(fp);
    }

    free(pbEncodedBlob);

    CertFreeCertificateContext(pSignerCert);
    CertFreeCertificateContext(pRecipCert);

    CertCloseStore(hStoreHandle, CERT_CLOSE_STORE_CHECK_FLAG);

    return 0;
}

void MyHandleError(const char* s)
{
    fprintf(stderr, "An error occurred in running the program. \n");
    fprintf(stderr, "%s\n", s);
    fprintf(stderr, "Error number %x.\n", GetLastError());
    fprintf(stderr, "Program terminating. \n");
    exit(1);
}


text:
Q: Sparse data clustering for extremely large dataset I have tried using

*

*kmeansparse, from sparcl packages (Lack of Memory error)

*bigkmeans from Biganalytics (Weird error: Couldn't find anything online;         Error in duplicated.default(centers[[length(centers)]]) :
   duplicated() applies only to vectors)

*skmean from skmeans (similar results as kmeans)

but I am still not able to get proper clustering for my sparse data. The clusters are not well defined, have overlapping membership for most part. Am I missing something in terms of handling sparse data?
What kind of pre-processing is suggested for data? should the missing values be marked -1 instead of 0 for clear distinction? Please feel free to ask for more details if you have any ideas that may help.


text:
Q: Ransack search for price with Money-rails I'm using Ransack to add a search function to my rails app and I'm also using Money-rails gem to handle price and currency.
I want to enter a price in Dollars in the Ransack search field and then it converts it to cents in order to find it in the relevant table.
So basically the problem is how to convert the input form Dollars to cents before submitting the search with Ransack.
Search form:
<div class="form-group">
    <%= f.label :price_cents_gteq, "Price between" %>
    <%= f.text_field :price_cents_gteq %>
    <%= f.label :price_cents_lteq, "And" %>
    <%= f.text_field :price_cents_lteq %>
</div>

Thanks a lot in advance!

A: Custom predicate can solve the problem.
You can use formatter proc to convert dollar to cents. Problems can arise  when you will display ransack object value of price.
Update #1
Or even better, you can solve it with ransacker class method.
Update #2
Here is the raw solution with model and ransaker method:
# model
ransacker :price_money, type: :integer, formatter: proc { |dollars| dollars * 100 } do |p|
  p.table[:price_cents]
end

# form in view
<%= f.number_field :price_money_gteq %>
<%= f.number_field :price_money_lteq %>


text:
Q: What's the best site/book to a J2SE programmer start to study J2ME? I'm a J2SE programmer from 3 years, and I would like to start studing about J2ME, which is the best site/book to start?

A: I would advise this book because it is recent for a J2ME book and because using a Symbian device for your first development efforts will have the huge advantage of being easily able to use Exception stack traces to find problems.
You will want to look into resources directly from Sun/Oracle and the JCP.
Sony-Ericsson and Nokia have invested huge amounts in developing J2ME technologies.


text:
Q: Compiling Nano with UTF-8 support on one computer failed I want to compile Nano from source for my friend.
I have successfully compiled it on all of my computers and he's having Linux Mint 18.1 too.
I don't know why; or better said I don't know what is missing in his system for UTF-8 support as per this configuration message:

*** Insufficient UTF-8 support was detected in your curses and/or C
*** libraries.  If you want UTF-8 support, please verify that your slang
*** was built with UTF-8 support or your curses was built with wide
*** character support, and that your C library was built with wide
*** character support.

I tried to install various development packages and it solved several other issues, but this one I am unable to solve since I didn't manage to google much about this issue.
I am quite exhausted, so I temporarily installed the compiled Nano editor with disabled UTF-8 support on his computer.
Any clues appreciated.

A: It looks like you need to install libncursesw5-dev and/or libslang2-dev; that's what's missing according to the config log.


text:
Q: error: attempt to call function 'is_colliding' in base 'null instance' on a null instance I've just started making a basic fps in the Godot engine, and I'm currently stuck on making a basic Raycast weapon. I've looked up tutorials from Coding With Tom, Gabaj YT, and multiple others, and yet no matter which one, I always end up writing the same piece of code:
if Raycast.is_Colliding:
and no matter how exactly I copy it down, I always end up with the same error:
error: attempt to call function 'is_colliding' in base 'null instance' on a null instance.

A: Raycast is a class. And is_colliding is one of its methods. But it is not an static method, you need an instance of Raycast.
Chances are, you do have an instance. If you have been following the tutorials, presumably you have a Raycast node in the scene tree added from the editor, and it is called… let me guess… Raycast. Yes, I do it too. Until it begins to be an issue and I rename it to something more meaningful or go for a different approach, but I digress.
The issue is that you are not referring the Raycast instance. You can reference nodes from your script using $, like this: $Raycast. It is a shorthand for using the get_node method. See Nodes and scene instances. To be clear, what you put after $ is the relative path on the scene tree, so it might not be just the name of the node. Here I'm assuming the node is a direct child of the node that has the script you are writing.
Thus, I would expect code like this:
if $Raycast.is_colliding():

Granted, you will see code that does look like this:
if raycast.is_colliding():

That is because somewhere in the script they have a line that looks something like this:
onready var raycast := $Raycast

Which declares a variable raycast and - on ready - sets it to a reference to the node, and then they can continue using that variable form there. With video tutorials some might skim over that. Here I found it on a Garbaj video on the topic: Godot FPS Hitscan Weapons Tutorial at 1:52


text:
Q: server side cd on sftp client connect Is there a way with sftp to have it configured server-side to run a cd command when a client connects?
I have my users thrown in to chroot, the folder has to be root:root chowned and cannot be writable by any other users, there are subfolders owned by the sftp users in the chroot.
What I'd like to do is cd users in to their folders from the server side in the jail when they connect, to avoid the annoyance of having to do so every time they connect. Is this possible?

A: OpenSSH uses a program called sftp-server to handle the server side of SFTP sessions. Sftp-server takes an option -d to specify the user's starting directory, as an alternative to their home directory. See the sftp-server man page.
If you're using a typical SFTP chroot jail setup, you probably have a line in your sshd_config:
ForceCommand internal-sftp

This causes sshd to run a copy of the sftp-server code which is built into the sshd program. You can add command-line arguments to this line, just like those for the standalone sftp-server program. So, for example:
Match User jdoe
    ChrootDirectory /var/jdoe-root
    ForceCommand internal-sftp -d /jdoe-homedir

When "jdoe" logs in, he'll be chrooted to /var/jdoe-root, and his starting directory for the session will be /var/jdoe-root/jdoe-homedir.

A: The SFTP protocol/session is state-less. There's no concept of a working directory with SFTP, contrary to a shell or an FTP. Any illusion of the working directory is simulated by the SFTP client.
So you cannot enforce it server-side.
Note how there's CWD command in FTP protocol (used in the background by cd command of a typical FTP client), but nothing similar in SFTP protocol (really meaning the protocol, not cd command in a typical SFTP client).


text:
Q: Adding Javascript Counter to my Images I'm trying to add a JavaScript counter to the images I'm pulling in through an instagram API. The hope is by adding a counter I can give the images a unique ID, allowing me to manipulate them into a slider. I've just started learning about counters and any help would be greatly appreciated!

Here's the page I'm working on with the images: http://carabinercoffee.com/instagram.html

Below is the code I'm using with the instafeed.js plugin. I think there might be a way to use the template section to work in something but that's just a guess.

A: If you simply want to issue each a tag an id, you can use the following code:
var aTags = document.getElementsByTagName('a');

for (var i = 0; i < aTags.length; i++) {
    aTags[i].setAttribute("id", i);
}

This code will cycle through all a tags in your current page and issue an incremental id.
Before:
  Test
  Test
  Test
  Test
  Test

After:
  Test
  Test
  Test
  Test
  Test

A: mwilson's answer along with a small add into the instafeeed code worked out this problem. I needed to add an after function into the plugin's code for mwilson's solution to take effect. here's the code:


text:
Q: Как закрасить границу объединённой ячейки через Google App Script? В столбце "A" перечислены запчасти авто, многие из строк объединены между собой (только в столбе "A"). После каждой запчасти идёт граница во всю строку. Раньше делал их в ручную, сегодня решил исправить это с помощью скрипта.
Расскажу о скрипте, как работает:
Поскольку я заранее не могу знать о всех дополнительных свойствах запчастей, я сначала через цикл удаляю все нижние границы, после использую данный цикл:
  var ranges = [];

  for(var i = 1; i < firstColumn.length; i++)
  {
    if(firstColumn[i][0])
    {
      ranges.push("A" + i + ":" + i);
    }
  }

Он определяет, где заканчивается объединённая ячейка и после я закрашиваю границу:
return sheet.getRangeList(ranges).setBorder(null, null, true, null, null, null);

Всё работает, как надо, но везде, где есть объединённые ячейки граница не прорисовывается.
Как это исправить?


text:
Q: Angular table component I want to develop a table in my Angular web app. Coming from a jQuery world, I had access to plugins like datatable, which was really flexible to customize.
Thinking in Angular components, I have the following two approaches to implement my table, please let me know what approach you have taken and why:
1) A single component for the whole table
2) Individual component for rows. So the table will be a parent component and the rows will be its child component


text:
Q: Does MySQL support secure credit transactions? I've been engaged to design and produce a website for my local grocer. They want to have purchases made through the website and I envisage that they will be keeping customer data.  But what I would really like to know is can I securely store credit card details in a MySQL database? Could you please describe the process, generally, for achieving this.

A: Yes and no, you can store data securely via encryption and/or hashing in MySQL. MySQL is just a relational database, you can use such a relational database to store securely customer data, and you can use it to store it insecurely.
Anyway, doing this thing right is hard, really hard, be it with MySQL or with any other database.
I recommend using a third party service to handle the transactions, there are various companies on this space competing with the big ones (Amazon, PayPal, Google.)

A: MySQL is a database, not an order processing software. It is your, programmer's task to make your MySQL transactions code secure. So the answer is both yes and no.


text:
Q: Parse string as resource name I have image resources in my /res folder for, say, thumbs. Now, I have 30 thumbs and what I do now to initiate array is:
Drawable[] thumbs = new Drawable[30];
thumbs[0] = context.getResources().getDrawable(R.drawable.thumb_01);
thumbs[1] = context.getResources().getDrawable(R.drawable.thumb_02);
thumbs[2] = context.getResources().getDrawable(R.drawable.thumb_03);
//this way 27 times more

Is there a way to loop this somehow without creating a long array?

A: I hope I'm understanding your question correctly. If so, I have a very similar situation in an app I'm developing. What you could do is declare an array of Drawables and add each new Drawable to the array as you loop through each 'thumb' in your resources. I assume there to be a finite number of thumbs since you are retrieving them from your resources. If that's the case, you can also specify in your file that contains the thumbs how many thumbs there are.
//assume you assign the number of thumbs to integer 'R.integer.numberofthumbs'
int numberOfThumbs = context.getResources().getInteger(R.integer.numberofthumbs);
Drawable[] thumbs = new Drawable[numberOfThumbs];

for(int i = 0; i < numberOfThumbs; i++){
    thumbs[i]= getResources().getDrawable(getResources().getIdentifier("thumb_" + i, "drawable", getPackageName()));
}

This is essentially the method I use in my code, and it works perfectly. Because of the naming in the for loop your thumbs labeled with numbers under 10 will have to have no leading zero. This could easily be changed to suit your current naming method, however. Hope I'm not too far off and this actually helps.
Cheers

A: You can create an int array that will hold the values of your drawable resources. Then just loop through this array.
int [] array = {R.drawable.thumb_01, R.drawable.thumb_02, ...};
Drawable[] thumbs = new Drawable[array.length];
for(int i = 0; i < array.length; i++){
    thumbs[i] = context.getResources().getDrawable(arr[i]);
}

EDIT :
It seems that your drawables' names follows a certain logic. So you can use getIdentifier (String name, String defType, String defPackage) :
Drawable[] thumbs = new Drawable[theLength];
Resources r = context.getResources();
for(int i = 0; i < theLength; i++){
    String name = i < 10 ?  "thumb_0"+i : "thumb_"+i;
    int drawableId = r.getIdentifier(name, "drawable", context.getPackageName());
    thumbs[i] = r.getDrawable(drawableId);
}

A: Finally, I got it with less code possible, and without creating array with ints or Drawables.
Create /res/values/array.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="thumbs">
    <item>@drawable/thumb_01</item>
    <item>@drawable/thumb_02</item>
    <item>@drawable/thumb_03</item>
    <item>@drawable/thumb_04</item>
    <item>@drawable/thumb_05</item>
    <item>@drawable/thumb_06</item>
    <item>@drawable/thumb_07</item>
    <item>@drawable/thumb_08</item>
    <item>@drawable/thumb_09</item>
    <item>@drawable/thumb_10</item>
    <item>@drawable/thumb_11</item>
    <item>@drawable/thumb_12</item>
    <item>@drawable/thumb_13</item>
    <item>@drawable/thumb_14</item>
    <item>@drawable/thumb_15</item>
    <item>@drawable/thumb_16</item>
    <item>@drawable/thumb_17</item>
    <item>@drawable/thumb_18</item>
    <item>@drawable/thumb_19</item>
    <item>@drawable/thumb_20</item>
</string-array>
</resources>

In code
TypedArray thumbs = context.getResources().obtainTypedArray(R.array.thumbs);
//in the loop
image.setImageDrawable(context.getResources().getDrawable(thumbs.getResourceId(i, 0));


text:
Q: GIT или Maven? Что выбрать для Java? Здравствуйте, вопрос может быть не совсем корректный, но всё же интересно мнения бывалых. Работаю с Java, когда начал  изучение не думал о таких вещах как репозитории, контроль версий, а сейчас остро возникает вопрос - git или Maven?
Интересны за-против, минусы-плюсы.

A: Git - это система контроля версий исходного кода.
Maven - инструмент сборки проекта и управления зависимостями.
Их задачи совершенно разные, и вы смело можете использовать и то и другое.


text:
Q: Python 3 urllib encoding I have a piece of code in Python 3 that retrieves information from a website :
webpage = urllib.request.urlopen('http://www.bdm.insee.fr/bdm2/index.action')
webpage = webpage.read()
webpage = webpage.decode("ISO-8859-1")
parser = etree.HTMLParser()
tree = etree.fromstring(webpage,parser)
for liste in tree.iterfind(".//ul"):
   print(etree.tostring(liste, pretty_print=True).decode("utf-8"))

I don't understand why some characters are rightly encoded while others aren't. Here is a portion of the output :

Souscription

Lettre d'information

Plan du site

Acheter les publications

Mentions légales et crédits

What are those &#13?
Thanks,
Michael

A: Those are carriage returns.  I suspect etree is explicitly including them so that the whitespace will be preserved, much like using   to preserve space.  That's a guess, though; I don't see
 in the original source, so I'm not clear why etree's going out of its way to preserve it.


text:
Q: Access the element of outer function in nested functions in jquery I have an each function that has change function and ajax inside..
$( ".spring_explorations" ).each(function() {
        $("#" + this.id + " select").change(function() {
            alert("t");
            $.ajax({
                type: 'POST',
                url: ('/admin/applications/get_sections_for_modal'), //pass query string to server
                data: {
                exploration_id: $("#" + this.id + " select").val()
                },
                success: function (response) {
                    $(this).parents('span').next().show();
                    $(this).parents('span').next().find("select").html(response);
                    console.log(response);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log(thrownError);
                }
            })
        });
    });

I would like to access the $(this) element of spring_explorations class inside the success snippet of ajax script.
I was able to access the element of the change function by adding context: this but how can I get the element of the outer?
Thanks in advanced.
Edit:
The $(this).parents('span').next().show(); and so on are undefined because maybe the this is the ajax itself not the spring_explorations class.
I'm very sorry if this is a duplicated question. I'm just fairly new in javascript and I think this is the right place to ask this thing. If you think this is not appropriate, just close my question.

A: Just store this in a variable. It tends to be named that or me or some other type of synonym for representing this.
$( ".spring_explorations" ).each(function() {
    var that = this;
       //^ store this into variable
    $("#" + this.id + " select").change(function() {
        alert("t");
        $.ajax({
            type: 'POST',
            url: ('/admin/applications/get_sections_for_modal'), //pass query string to server
            data: {
            exploration_id: $("#" + this.id + " select").val()
            },
            success: function (response) {
                $(that).parents('span').next().show();
                //^ re-use stored `this` value
                $(that).parents('span').next().find("select").html(response);
                console.log(response);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(thrownError);
            }
        })
    });
});

A: You need to reference this from the context you want to use it in. You can use the references within nested scopes where as the value of this will change depending on the scope, as you have found out.
$( ".spring_explorations" ).each(function() {
    var _this = this;
    // You now have a reference to the node in the variable _this
    // that can be used anywhere within this functions scope

    $("#" + this.id + " select").change(function() {
        var self = this;
        // Self is now a reference to the changed element
        // that can be used within this functions scope

        // your code here that uses _this and self when you please.
    });
});

A: why are you writing in each, you should be writing like this, if the elements are dynamic as you mentined in comments:
    $(".spring_exploration").on('change','select',function() {
         var element = this;
        alert("t");
        $.ajax({
            type: 'POST',
            url: ('/admin/applications/get_sections_for_modal'), //pass query string to server
            data: {
            exploration_id: $(element).val()
            },
            success: function (response) {
                $(element).parents('span').next().show();
                $(element).parents('span').next().find("select").html(response);
                $(element).closest(".spring_exploration") // you can access like this
                console.log(response);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(thrownError);
            }
        })
    });

and now you can access it using closest


text:
Q: Sorting rows at value with multiple hierarchical levels I have a list of hierarchical product prices with their prices already aggregated. The hierarchical levels are cluster, store and shelf.

I would like to sort these product prices hierarchically. Each level needs to be sorted. Here is an example of the expected result:

Right now, I can sort prices at shelf level but not at store or cluster level yet:
SELECT cluster_id, store_id, shelf_id, price FROM (
    SELECT * FROM (
        SELECT p.*,
            ROW_NUMBER () OVER (
                ORDER BY
                cluster_id ASC NULLS FIRST,
                store_id ASC NULLS FIRST,
                price DESC
            ) AS rn
        FROM (SELECT * FROM products) p
    )
)
ORDER BY rn;

My actual result is:

I'm using Oracle Database 12c.
Sample data
CREATE TABLE products (
    cluster_id     VARCHAR2(30),
    store_id       VARCHAR2(30),
    shelf_id       VARCHAR2(40),
    price          NUMBER(*,2)
);

INSERT INTO products VALUES ('10','230',NULL,120);
INSERT INTO products VALUES (NULL,NULL,NULL,500);
INSERT INTO products VALUES ('10','230','967',40);
INSERT INTO products VALUES ('10',NULL,NULL,300);
INSERT INTO products VALUES ('50','430','863',50);
INSERT INTO products VALUES ('50','170',NULL,70);
INSERT INTO products VALUES ('10','500','783',100);
INSERT INTO products VALUES ('50','170','798',20);
INSERT INTO products VALUES ('50','480',NULL,80);
INSERT INTO products VALUES ('50','430',NULL,50);
INSERT INTO products VALUES ('10','500',NULL,180);
INSERT INTO products VALUES ('50','480','486',60);
INSERT INTO products VALUES ('10','230','296',80);
INSERT INTO products VALUES ('50',NULL,NULL,200);
INSERT INTO products VALUES ('10','500','344',80);
INSERT INTO products VALUES ('50','480','234',20);
INSERT INTO products VALUES ('50','170','368',50);

A: I think this will work.
with t as (
  select cluster_id
  , store_id
  , shelf_id
  , price
  , row_number() over (partition by cluster_id order by price desc) cluster_sort
  , row_number() over (partition by cluster_id, store_id order by price desc) store_sort
  , row_number() over (partition by cluster_id, store_id, shelf_id order by price desc) shelf_sort
)
select cluster_id
, store_id
, shelf_id
, price
from t
order by cluster_sort
, store_sort
, shelf_sort
;

A: This ordering method gives desired output:
select p.*
  from products p
  order by
       sum(case when store_id is not null and shelf_id is not null then price end)
           over (partition by cluster_id) desc,
       sum(case when store_id is not null and shelf_id is not null then price end)
           over (partition by cluster_id, store_id) desc,
       case when shelf_id is null then 1 end, price desc


text:
Q: Вопрос по UTM-метках, не передаются в форме обратной связи, как решить? Суть вопроса в самом вопросе: необходимо в форму обратной связи (Ajax) добавить захват UTM-меток и соответственно сделать их передачу на mail. Я добавил, но почему-то на почту они не приходят. Вот мой код:
HTML-код

<form class="form-1" id="form-1">

Отправьте заявку на марс!

И наш марсианский менеджер перезвонит вам в ближйшее время.

    <input type="hidden" name="utm_source" value="<?php echo isset($_GET['utm_source']) ? $_GET['utm_source'] : '' ;?>">
    <input type="hidden" name="utm_medium" value="<?php echo isset($_GET['utm_medium']) ? $_GET['utm_medium'] : '' ;?>">
    <input type="hidden" name="utm_campaign" value="<?php echo isset($_GET['utm_campaign']) ? $_GET['utm_campaign'] : '' ;?>">
    <input type="hidden" name="utm_term" value="<?php echo isset($_GET['utm_term']) ? $_GET['utm_term'] : '' ;?>">
    <input type="hidden" name="utm_content" value="<?php echo isset($_GET['utm_content']) ? $_GET['utm_content'] : '' ;?>">
    <input type="hidden" name="formid" value="с первого экрана Pop-up">
    <input type="text" name="name" placeholder="Ваше имя" required>
    <input class="index__phone" name="code" type="tel" maxlength="3" placeholder="123" required>
    <input class="number__phone" name="tel" type="tel" placeholder="325-54-94" required>
    <button class="btn-submit-mars" type="submit">Отправить заявку на марс</button>

</form>

PHP-обработчик

$recepient = "xxx@gmail.com";
$sitename = "Марсоход";

$formid = trim($_POST["formid"]);
$utm_source = trim($_POST["utm_source"]);
$utm_medium = trim($_POST["utm_medium"]);
$utm_campaign = trim($_POST["utm_campaign"]);
$utm_term = trim($_POST["utm_term"]);
$utm_content = trim($_POST["utm_content"]);
$name = trim($_POST["name"]);
$code = trim($_POST["code"]);
$tel = trim($_POST["tel"]);
$message = trim($_POST["message"]);
$message = "форма $formid \nИсточник перехода: $utm_source $utm_medium $utm_campaign $utm_term $utm_content \nИмя: $name \nТелефон: $code $tel \nВопрос: $message";

$pagetitle = "Новое сообщение с сайта \"$sitename\"";
mail($recepient, $pagetitle, $message, "Content-type: text/plain; charset=\"utf-8\"\n From: $recepient");

js

$("#form-1").validate({
  rules: {
    name: {
      required: true,
      minlength: 2
    },

    code: {
      required: true,
      digits: true,
      minlength: 3,
      maxlength: 3
    },

    tel: {
      required: true,
      minlength: 7,
      maxlength: 9

    }
  },
  messages: {
    name: {
      required: "Неверно заполнено поле :(",
      minlength: "Минимальное кол-во символов 2"
    },
    code: {
      required: "Введите код",
      digits: "Обязательно цифры",
      minlength: "3 символа"
    },
    tel: {
      required: "Введите номер телефона :(",
      minlength: "Необходимо 7 символов"
    }
  }
});

$("#form-1").submit(function() {

  if ($("#form-1").valid()) {
    var th = $(this);
    $.ajax({
      type: "POST",
      url: "mail.php",
      data: th.serialize()
    }).done(function() {

      $(".success").addClass("visible");
      setTimeout(function() {
        // Done Functions
        th.trigger("reset");
        $(".success").removeClass("visible");
      }, 1000);

      $('#form-1')[0].reset(
        setTimeout(function() {}, 1000)
      );

      $("#form-1").hide();

      $('.mfp-bg.mfp-ready').css({
        'display': 'none'
      });

      $('#popUpMessage').removeClass('hiddenDiv');
      setTimeout(function() {
        $('#popUpMessage').addClass('hiddenDiv');
      }, 5000);
    });
  }
  return false;
});

в принципе ничего как будто сложного, но не работает. На форму приходит письмо: и там где Источник: .... Ключевое слово: ....
сама форма рабочая и проверена не раз.
Подскажите или покажите как правильно задать в форме эти метки, скажу честно google перерыл, примеры использовал - но толку никакого. Спасибо.

A: На мой взгляд, в данном коде было несколько ошибок. В приведенном ниже примере они должны быть исправлены:
$("#form-1").submit(function(e) {
  e.preventDefault(); // prevent doubly sending

  var form = $(this);

  if (form.valid()) {
    $.post({
      "mail.php",
      form.serializeArray().reduce(function(o, a) {
        o[a.name] = a.value;
        return o;
      }, {}), // post an object instead of string
      function(data) { // response from server is here
        form.submit(function(e) {
           e.preventDefault(); // no further submits allowed
        });

        $(":submit", form).prop("disabled", true);

        $(".success").addClass("visible");

        setTimeout(function() {
          form.trigger("reset").hide();
          $(".success").removeClass("visible");
        }, 1000);

        $('.mfp-bg.mfp-ready').css({
          'display': 'none'
        });

        $('#popUpMessage').removeClass('hiddenDiv');

        setTimeout(function() {
          $('#popUpMessage').addClass('hiddenDiv');
        }, 5000);
      }
    });
  }
});


text:
Q: fscanf in C - how to determine comma? I am reading set of numbers from file by fscanf(), for each number I want to put it into array. Problem is that thoose numbers are separated by "," how to determine that fscanf should read several ciphers and when it find "," in file, it would save it as a whole number? Thanks

A: This could be a start:
#include <stdio.h>

int main() {
    int i = 0;

    FILE *fin = fopen("test.txt", "r");

    while (fscanf(fin, "%i,", &i) > 0)
        printf("%i\n", i);

    fclose(fin);

    return 0;
}

With this input file:
1,2,3,4,5,6,
7,8,9,10,11,12,13,

...the output is this:
1
2
3
4
5
6
7
8
9
10
11
12
13

What exactly do you want to do?

A: I'd probably use something like:
while (fscanf(file, "%d%*[, \t\n]", &numbers[i++]))
    ;

The %d converts a number, and the "%*[, \t\n]" reads (but does not assign) any consecutive run of separators -- which I've defined as commas, spaces, tabs, newlines, though that's fairly trivial to change to whatever you see fit.

A: fscanf(file, "%d,%d,%d,%d", &n1, &n2, &n3, &n4); but won't work if there are spaces between numbers. This answer shows how to do it (since there aren't library functions for this)

A: Jerry Coffin's answer is nice, though there are a couple of caveats to watch for:

*

*fscanf returns a (negative) value at the end of the file, so the loop won't terminate properly.

*i is incremented even when nothing was read, so it will end up pointing one past the end of the data.

*Also, fscanf skips all whitespace (including \t and \n if you leave a space between format parameters.
I'd go for something like this.
int numbers[5000];
int i=0;
while (fscanf(file, "%d %*[,] ", &numbers[i])>0 && i<sizeof(numbers))
{
    i++;
}
printf("%d numbers were read.\n", i);

Or if you want to enforce there being a comma between the numbers you can replace the format string with "%d , ".


text:
Q: Convert datetime string from specific time zone to another specific timezone I have a HIVE table of orders from different locations. This table contains a string column containing the date and time of each order. There is also another column with the corresponding timezone.For some reason, however, the value in the timezone column is not the local one. Then for each date, I have the corresponding timezone and a target timezone to convert. Like this:
with orders as (
    select 1 as order_id, '2022-07-20 15:04:12' as create_time, 'UTC' as create_tz, 'BRT' as target_tz
    union all
    select 2 as order_id, '2022-07-20 17:34:14' as create_time, 'CET' as create_tz, 'PST' as target_tz
) select * from orders;

order_id
create_time
create_tz
target_tz

1
2022-07-20 15:04:12
UTC
BRT

2
2022-07-20 17:34:14
CET
PST

I need to print a string column with the local date and time (and also make the timezone explicit). Like this:

order_id
local_time

1
2022-07-20 12:04:12 BRT

2
2022-07-20 08:34:14 PST

My approach was to convert everything to UTC and then print it using the function from_unixtime, however it seems that this function always print the result in the client's time (in my case CST). I didn't find a way to set a target timezone for each record.
with orders as (
    select 1 as order_id, '2022-07-20 15:04:12' as create_time, 'UTC' as create_tz, 'BRT' as target_tz
    union all
    select 2 as order_id, '2022-07-20 17:34:14' as create_time, 'CET' as create_tz, 'PST' as target_tz
) select
    order_id,
    from_unixtime(unix_timestamp(concat(create_time, ' ', create_tz), 'yyyy-MM-dd HH:mm:ss z'),  'yyyy-MM-dd HH:mm:ss z')
from orders;

A: It is not an elegant workaround, but it seems to work:
with orders as (
    select 1 as order_id, '2022-07-20 15:04:12' as create_time, 'UTC' as create_tz, 'BRT' as target_tz
    union all
    select 2 as order_id, '2022-07-20 17:34:14' as create_time, 'CET' as create_tz, 'PST' as target_tz
) select
    order_id,
    concat(from_unixtime(
        unix_timestamp(create_time)
        + unix_timestamp(concat('1970-01-01 00:00:00', ' ', create_tz), 'yyyy-MM-dd HH:mm:ss z')
        - unix_timestamp(concat('1970-01-01 00:00:00', ' ', target_tz), 'yyyy-MM-dd HH:mm:ss z')
    ), ' ', target_tz)
from orders;


text:
Q: Django Form won't submit error says Select a Valid Choice ____ is not one of the available choices I built a form in django and I'm having trouble debugging my Tours Choices.  It is a ChoiceField and I use the CheckboxMultipleSelect Widget.  I don't know what I'm doing wrong to get the error in the screenshot below.  Any thoughts? Do I need to facilitate more information?  I'm a django newbie.
Picture of the Form Error

A: A form.ChoiceField lets you input exactly one choice for a form (out of a selection of several choices).  If you saved it to a database in a model there would be one value stored in the database.  Your CheckboxMultipleSelect widget is for a form.MultipleChoiceField where you can input multiple values.  So change your ChoiceField to a MultipleChoiceField in your form and you should be fine.  If you save this data to a model, that model would have to be an appropriate field, like a ManyToManyField if they are Foreign Keys.


text:
Q: Obtener total de dos input y diferencia de dos fechas automaticamente Tengo este código la diferencia de la fecha funciona pero tengo que presionar un botón para que llama la función lo que deseo es que sin presionar botón me aparezca la diferencia igual para el total de dos input
function calcular() {
  var fechaini = new Date(document.getElementById('fechaini').value);
  var fechafin = new Date(document.getElementById('fechafin').value);
  var diasdif = fechafin.getTime() - fechaini.getTime();
  var contdias = Math.round(diasdif / (1000 * 60 * 60 * 24));
  var preciodia = document.getElementById('preciodia').value;
  var preciototales = Math.round(contdias * preciodia);

  if ((new Date(fechaini).getTime() > new Date(fechafin).getTime())) {
    alert('la fecha es menor');
    return false;
  } else {
    document.getElementById('dias').value = contdias;
    return true;
  }
  if (preciototales == null) {
    alert("error al obtener el total");
  } else {
    document.getElementById('preciototal').value = preciototales;
  }

}

A: Si tu pagina se muestra con los valores cargados al inicio simplemente introduce la llamada la función que has declarado para que se ejecute.
function calcular() {
  var fechaini = new Date(document.getElementById('fechaini').value);
  var fechafin = new Date(document.getElementById('fechafin').value);
  var diasdif = fechafin.getTime() - fechaini.getTime();
  var contdias = Math.round(diasdif / (1000 * 60 * 60 * 24));
  var preciodia = document.getElementById('preciodia').value;
  var preciototales = Math.round(contdias * preciodia);

  if ((new Date(fechaini).getTime() > new Date(fechafin).getTime())) {
    alert('la fecha es menor');
    return false;
  } else {
    document.getElementById('dias').value = contdias;
    return true;
  }
  if (preciototales == null) {
    alert("error al obtener el total");
  } else {
    document.getElementById('preciototal').value = preciototales;
  }

}

calcular();

Si por el contrario los valores son introducidos por el usuario y quieres que se muestre el resultado sin pulsar un botón debes asociar la función a eventos tales como onKeyUp o onBlur de los input donde escriba. En este caso debes controlar excepciones al intentar convertir a fechas.


text:
Q: What's the fastest way to run integration tests against a rails app with significant database seeds? I've got a ruby on rails application with significant database seeds that tie into the UI elements and are thusly required for integration tests.
I'm using database_cleaner to clean up after my tests, but due to the heavy js use of the application most of my tests can't be run with the transaction strategy which allows me to specify tables to leave out of the rollback.
The result is that I've got to re-seed the database before each test or deal with a dirty database. Does anyone have tips for testing in this kind of situation or know of any tools that may help?
Thanks!

A: I've dealt with this in the past by using transactions for our tests (we're using something a little homegrown for that at the moment but previously we used database cleaner).
The key is forcing everything to use the same database connection. The path I've been down for this is to set the database pool size in test to 1: everyone has to share the same connection because active record won't let you create more connections.
For this to work you need to be careful about releasing connections no longer in use, by calling ActiveRecord::Base.clear_active_connections!
There are 2 places you need to do this

*

*when your test code is about to call visit, click etc.

*after each request (use a Rack middleware for this- you can basically copy ActiveRecord::ConnectionAdapters::ConnectionManagement)

This works for us writing specs against pages that use ajax to fetch intermediate data and so on, but can be a bit tricky to get working initially. I wrote about it more extensively a while back


text:
Q: Error deleting single list item from context menu I am working on a note application. I have implemented a note Adapter class to show list items and Note Serializable.  I am trying to delete a single list view item from a context menu after showing alert dialog. For now i am getting crashes, don't know what am doing wrong.
Main Activity
    public boolean onContextItemSelected(final MenuItem item) {
            final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
          final  Note mLoadedNote = (Note) mListNotes.getAdapter().getItem(info.position);
            mLoadedNote.getTitle();
            switch (item.getItemId()) {

                case R.id.delete:
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this)
                            .setTitle("Delete " +  mLoadedNote.getTitle())
                            .setMessage("are you sure?")
                    .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        here is where am getting the error
                        if(mLoadedNote != null) {
                            ArrayAdapter<String> note = (ArrayAdapter<String>) mListNotes.getAdapter().getItem(info.position);
    note.remove(note.getItem(info.position));
                            note.notifyDataSetChanged();
                            Toast.makeText(MainActivity.this,  mLoadedNote.getTitle() + " is deleted", Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(MainActivity.this,  "can not delete the note '" + mLoadedNote.getTitle() + "'", Toast.LENGTH_SHORT).show();
                        }

                    }
                    })
                        .setNegativeButton("NO", null); //do nothing on clicking NO button :P
                    alertDialog.show();
            }
            return super.onContextItemSelected(item);
        }

Note Adapter
   public class NoteAdapter extends ArrayAdapter<Note> {

    public static final int WRAP_CONTENT_LENGTH = 50;
    public NoteAdapter(Context context, int resource, List<Note> objects) {
        super(context, resource, objects);
    }

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

        if(convertView == null) {
            convertView = LayoutInflater.from(getContext())
                    .inflate(R.layout.view_note_item, null);
        }

        Note note = getItem(position);

        if(note != null) {
            TextView title = (TextView) convertView.findViewById(R.id.list_note_title);
            TextView date = (TextView) convertView.findViewById(R.id.list_note_date);
            TextView content = (TextView) convertView.findViewById(R.id.list_note_content_preview);

            title.setText(note.getTitle());
            date.setText(note.getDateTimeFormatted(getContext()));

            //correctly show preview of the content (not more than 50 char or more than one line!)
            int toWrap = WRAP_CONTENT_LENGTH;
            int lineBreakIndex = note.getContent().indexOf('\n');
            //not an elegant series of if statements...needs to be cleaned up!
            if(note.getContent().length() > WRAP_CONTENT_LENGTH || lineBreakIndex < WRAP_CONTENT_LENGTH) {
                if(lineBreakIndex < WRAP_CONTENT_LENGTH) {
                    toWrap = lineBreakIndex;
                }
                if(toWrap > 0) {
                    content.setText(note.getContent().substring(0, toWrap) + "...");
                } else {
                    content.setText(note.getContent());
                }
            } else { //if less than 50 chars...leave it as is :P
                content.setText(note.getContent());
            }
        }

        return convertView;
    }

}

Note.java
public class Note implements Serializable {
    private long mDateTime; //creation time of the note
    private String mTitle; //title of the note
    private String mContent; //content of the note

    public Note(long dateInMillis, String title, String content) {
        mDateTime = dateInMillis;
        mTitle = title;
        mContent = content;
    }

    public void setDateTime(long dateTime) {
        mDateTime = dateTime;
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public void setContent(String content) {
        mContent = content;
    }

    public long getDateTime() {
        return mDateTime;
    }

    /**
     * Get date time as a formatted string
     * @param context The context is used to convert the string to user set locale
     * @return String containing the date and time of the creation of the note
     */
    public String getDateTimeFormatted(Context context) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"
                , context.getResources().getConfiguration().locale);
        formatter.setTimeZone(TimeZone.getDefault());
        return formatter.format(new Date(mDateTime));
    }

    public String getTitle() {
        return mTitle;
    }

    public String getContent() {
        return mContent;
    }
}

Error
FATAL EXCEPTION: main
                                                                       Process: com.app.ben.notetaker, PID: 27476
                                                                       java.lang.ClassCastException: com.app.ben.notetaker.Note cannot be cast to android.widget.ArrayAdapter
                                                                           at com.app.ben.notetaker.MainActivity$2.onClick(MainActivity.java:103)
                                                                           at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

A: Change this:
ArrayAdapter<String> note = (ArrayAdapter<String>) mListNotes.getAdapter().getItem(info.position);

to this:
ArrayAdapter<Note> note = (ArrayAdapter<Note>) mListNotes.getAdapter();

Also, it's not good to use note as a name for ArrayAdater var. Rename it to notesArrayAdapter, or something similar.


text:
Q: Use CSS in Conditional Statements I'm fairly new to coding with CSS and PHP
To be more specific, is it possible to use "display:" for a if-else statement?
I'm trying to use pre-made variables and then get the sum of variables currently visible to the screen, which has

"display: block;"

and ignore the value of variables that has

"display: none;".

Thanks, in advance
I don't really have code for this but I'm trying to
var a = 1;
var b = 2;
var c = 3;

let's say a and b are visible by
display: block;

then a function where it will scan all variables and then add all that is currently visible(which is var a and b)

A: I don't know if I have quite understand what you want to do but here is the solution on what I have understood.
If you want to show hide on if and else then with jQuery you can use like this
if(true){
  $('.myClass').show();
}else{
  $('.myClass').hide();
}

If you want to use with PHP and CSS then add a class in div and write a css
e.g :
CSS
.myClass.show{
  display:block;
}
.myClass.hide{
  display:none;
}

PHP
<?php
$val = 'show';

  if(false){
    $val = 'hide';
  }
?>

<div class="myClass <?php echo $val ?>">Text </div>


text:
Q: How to Implement an edit view for a list of objects in MVC 4 in its most elegant way? I've got a "ContactInfo" view in which I want to get a list of different phone numbers of different types from the user. The user should be able to add, edit and delete numbers and specify their types. At least one mobile number is required.
I've tried different approaches and I've come to a dead-end at some point. I thought describing the whole scenario and asking for a solution would be more efficient than to ask specific bugs. I'd be thankful for your answers.
Here is my phone class:
public partial class Phone
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public string Number { get; set; }
    public PhoneNumberType Type { get; set; }

    public virtual User User { get; set; }
}

and here is the phone type enum:
public enum PhoneNumberType
{
    None,
    Mobile,
    Home,
    Work
}

This is the model for the view (I have also included a list that populates phone types from the enum to fill the type combobox):
public class ContactInfoModel
{

    public int Id { get; set; }

    public string EmailAddress { get; set; }
    public string Country { get; set; }
    public string Province { get; set; }
    public string County { get; set; }
    public string City { get; set; }
    public string Address { get; set; }
    public ICollection<Phone> Phones { get; set; }

    private IEnumerable<EnumMember> _phoneTypes;
    public IEnumerable<EnumMember> PhoneTypes
    {
        get
        {
            if (this._phoneTypes == null)
            {
                _phoneTypes = EnumUtility.GetEnumMembers(typeof(PhoneNumberType));
            }
            return _phoneTypes;
        }
    }
}

And finally this is the view:
@model Jobeteria.Models.JobSeekers.ContactInfoModel

@{ViewBag.Title = "Contact Information";}

@using (Html.BeginForm()){
@Html.AntiForgeryToken()

    <hgroup>

@ViewBag.Title

    </hgroup>

        <fieldset>
            <legend>Contact Information</legend>

                    @*view to manipulate phone numbers*@

                    @Html.LabelFor(model => model.EmailAddress)
                    @Html.EditorFor(model => model.EmailAddress)

                    @Html.ValidationMessageFor(model => model.EmailAddress)

                    @Html.LabelFor(model => model.Country)
                    @Html.EditorFor(model => model.Country)

                    @Html.ValidationMessageFor(model => model.Country)

                    @Html.LabelFor(model => model.Province)
                    @Html.EditorFor(model => model.Province)

                    @Html.ValidationMessageFor(model => model.Province)

                    @Html.LabelFor(model => model.County)
                    @Html.EditorFor(model => model.County)

                    @Html.ValidationMessageFor(model => model.County)

                    @Html.LabelFor(model => model.City)
                    @Html.EditorFor(model => model.City)

                    @Html.ValidationMessageFor(model => model.City)

                    @Html.LabelFor(model => model.Address)
                    @Html.TextAreaFor(model => model.Address)

                    @Html.ValidationMessageFor(model => model.Address)

                    <input type="submit" value="SAVE" />
                    <input type="reset" value="Cancel" onclick="javascript: history.back(1);"/>

        </fieldset>

}

A: I always find model binding to Enumerable items a bit of a pain - that is essentially what you are trying to achieve right, allow the user to edit a list of phone numbers?.
In terms of validation, I would write a custom validation attribute to use in your View Model - this will check that at least one phone number is present.
Phil Haack has bloged about binding to lists here:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Adapting from Phil's post I think you will have to do something like this:
<% for (int i = 0; i < userPhoneNumeberCount; i++) { %>

  <%: Html.TextBoxFor(m => m.Phones[i].Number ) %>
  <%: Html.SelectListFor(m => m.Phones[i].Type, PhoneNumberSelectListData ) %>
<% } %>


text:
Q: Batch file to rename folders while retaining numbering system I'm attempting to write a windows .bat file code that renames all folders in a directory to something else while keeping the number at the end.  For example "DVD#4" to "Test Folder 4".  I've been trying to alter the various file renaming codes here, but it hasn't worked.  How should I write this?

A: If all folders have a # character followed by a number, try this (untested) code. Save it inside a batch file and then invoke via a cmd instance.
This test assumes some folder paths. Modify to suit your needs.
pushd C:\ParentOfDVDFolders
for /f "tokens=1,2 delims=#" %%a in ('dir /b /ad DVD*') do ren "%%~fa#%%b" "Test Folder %%b"
popd