text:
Q: adding created timestamp to join table in doctrine2 I have the following property in my User entity to track followers and following. Basically a user can follow other user as well. I have a join column called app_user_follow_user, however I also wanted to add a timestamp of whenever someone follows another user, when did it happen. How can I specify a created timestamp via this ORM?
/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="following")
 */
protected $followers;

/**
 * @ORM\ManyToMany(targetEntity="User", inversedBy="followers")
 * @ORM\JoinTable(name="app_user_follow_user",
 *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="follow_user_id", referencedColumnName="id")}
 *      )
 */
protected $following;

A: Doctrine ManyToMany relationships are used when your join table has two columns. If you need to add another column you have to convert the relationship to OneToMany on both sides and ManyToOne on the joined entity.
This is entirely untested but it will hopefully give you the gist.
User Entity
/**
 * @ORM\OneToMany(targetEntity="AppUserFollowUser", mappedBy="appUser")
 */
protected $followers;

/**
 * @ORM\OneToMany(targetEntity="AppUserFollowUser", mappedBy="followUser")
 */
protected $following;

AppUserFollowUser Entity
/**
 * @ORM\Table(name = "app_user_follow_user")
 */
class AppUserFollowUser
{
    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="User", inversedBy="followers")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     * })
     */
    private $appUser;

    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="User", inversedBy="following")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="follow_user_id", referencedColumnName="id")
     * })
     */
    private $followUser;

    /**
     * @ORM\Column(name="created_date", type="datetime", nullable=false)
     */
    private $createdDate;
}

A: I think that you will have to create  a link entity manually (entiy1 onetomany linkEntity manytoone entity2.
Because, the usual link entity are automated and should be as simple and (data less) as possible, so doctrine can take all the controle over it,
imagine you need to get the timestamp, how can you do it on an (none hard coded) entity, you will need a getter, and the annotations are not supposed to contains code.


text:
Q: Load local JSON into electron, can't use require/include I've been refactoring this code into public and I'm using this to solve some past mistakes. Like writing my save and load functions.

I need to load in my code some JSON files. Doesn't matter where if I
  can access it here
  https://github.com/cicerohellmann/3DBRPG/blob/board/board/boardView.js

I've run into most of the possible solutions when trying to bring a file inside of electron or work arounds for not being able to use require or include in my js files after opening my project with electron instead of node.
window.fs = require("fs") wont do,
preloading with electron I couldn't make it work (this is actually my best shot yet),
<script>
    window.nodeRequire = require;
    delete window.require;
    delete window.exports;
    delete window.module;
</script>
<script type="text/javascript" src="jquery.js"></script>

doesn't work either
the branch I'm working is this one https://github.com/cicerohellmann/3DBRPG/tree/board even then I should be working our something in a branch called "save/load"

A: I found a solid solution that doesn't raise any security flags, for now:
This is my main.js create window method:
function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  });
  mainWindow.loadFile('index.html')
  mainWindow.on('closed', function () {
    mainWindow = null
  });
}

Observe that I added "__dirname", which is a method that grabes the current path, and added my preload.js script
this is my preload.js script:
window.fs = require('fs');
window.path = __dirname;

I found very usefull to import this "__dirname" method with it since the current path for my local files will probably change in the future and other people machines.
now you can load and save files using "window.fs"
Here is my dataManagement class: https://github.com/cicerohellmann/3DBRPG/blob/dataManagement_save_load/dataManagement.js

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can we do a bulk index without specifying a document ID for Elasticsearch? Is it possible to do a bulk index without specifying a document ID? I want Elasticsearch to generate a random ID for me while indexing, but can it be done?

A: Here is another example of bulk upload without specifying the _id.
`
curl -XPOST "http://localhost:9200/_bulk" -d'
    { "index" : { "_index" : "test", "_type" : "demo" } }
    { "title" : "Quick brown rabbits", "content" : "Brown rabbits are commonly seen" }
    { "index" : { "_index" : "test", "_type" : "demo" } }
    { "title" : "Keeping pets healthy", "content" : "My quick brown fox eats rabbits

`
Response is below
`
{
  "took": 451,
  "errors": false,
  "items": [
    {
      "create": {
        "_index": "test",
        "_type": "demo",
        "_id": "AVYDtp_fxosF2Bdj7ghV",
        "_version": 1,
        "_shards": {
          "total": 2,
          "successful": 1,
          "failed": 0
        },
        "status": 201
      }
    },
    {
      "create": {
        "_index": "test",
        "_type": "demo",
        "_id": "AVYDtp_fxosF2Bdj7ghW",
        "_version": 1,
        "_shards": {
          "total": 2,
          "successful": 1,
          "failed": 0
        },
        "status": 201
      }
    }
  ]
}

`

A: Yes you can!
Tested on 0.90.0.Beta1:
$ cat requests
{ "index" : { "_index" : "test", "_type" : "type1" } }
{ "field1" : "value1" }

$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests; echo
{"took":6,"items":[{"create":{"_index":"test","_type":"type1","_id":"IWqsRqyhRVq-F69OLIngTA","_version":1,"ok":true}}]}


text:
Q: jsp:include pointing to controller method not working on controller return I am using a JSP:include tag on every view to show my menu.  Yesterday i found out that you can actually include a controller method which is very neat because it allows me to do some processing before returning the menu.  What I am doing is i'm adding this to every page :
<jsp:include page="/menu/showMenu"/>

I used to do just this :
<%@ include file="menu.jsp" %>

This change allows me to pass boolean values to the model when the menu is returned which i am using to either display or not display certain options depending on what the user has access to.  This works perfectly when first loading a page but the menu completely disappears when any sort of controller processing is done.  For example, i have a log page with a table showing log entries from the database.  The column headers contain search fields which are part of a form that, when submitted, calls a controller method to filter the log list and display the filtered data.  The return statement from that controller method is simply :
return "logs";

This works perfectly when using the original include that points to the actual JSP file instead of the controller method but with the new approach of including a controller method the menu vanishes when the filtering logic returns the page.  What i can always do is include the JSP file as i used to and place the service calls in the JSP directly to check whether the user has access to each function but i really prefer the idea of having a controller doing this stuff and passing boolean values to the JSP.
Any idea why i'm seeing this behavior?  I can provide code examples if necessary.
Thanks!

A: I figured it out! I had to add a POST method to my menu controller. It does exactly the same thing as the GET method but it is necessary when included in a page that is returned from another controller's POST method. Hopes this can help someone!


text:
Q: Unable to fetch values of range of cells in custom function I was working on a problem which requires input an array and output is also an array. I wrote the VBA code (after I had done workings of logic on notebook) but I don't know why this code is unable to fetch values of input.
I have already written the code. Just help me with the syntax!
As I am not a professional coder, please ignore the naming of variables. Also, I am new to this platform, so I am not aware of many rules. Any help will really be appreciated. Thanks!
Test cases and error:

Public Function Get1_GEM(vector As Range)
Dim i As Long, j As Long, i1 As Long, j1 As Long
Dim a As Long, b As Long, c As Long
Dim GEM() As Double
ReDim GEM(1 To 3, 1 To 2) As Double
Dim res() As Double
ReDim res(1 To 3) As Double
Dim row() As Double
ReDim row(1 To 3) As Double
For i = 1 To 3 Step 1
    For j = 1 To 2 Step 1
        GEM(i, j) = 2 * i + j - 2
        row(i) = 0
    Next j
Next i
Dim inp() As Double
ReDim inp(1 To 3) As Double
i = 0
j = 0
Dim x() As Double
ReDim x(1 To 3) As Double
Dim y() As Double
ReDim y(1 To 3) As Double
i = 0
For i = 1 To 3 Step 1
    inp(i) = vector.Cells(i, 1)
Next i

For i = 1 To 3 Step 1
    For j = 1 To 2 Step 1
        If GEM(i, j) = inp(1) Then
            x(1) = i
            y(1) = j
            row(i) = row(i) + 1
        ElseIf GEM(i, j) = inp(2) Then
            x(2) = i
            y(2) = j
            row(i) = row(i) + 1
        ElseIf GEM(i, j) = inp(3) Then
            x(3) = i
            y(3) = j
            row(i) = row(i) + 1
        End If
    Next j
Next i
i = 0
j = 0
If row(1) > 0 And row(2) > 0 And row(3) > 0 Then
    For i = 1 To 3 Step 1
        res(i) = GEM(x(i), 2 - y(i))
    Next i
Else

    If row(1) = 0 Then
        a = 0
    ElseIf row(2) = 0 Then
        a = 1
    ElseIf row(3) = 0 Then
        a = 2
    End If

    If row(1) = 1 Then
        b = 0
    ElseIf row(2) = 1 Then
        b = 1
    ElseIf row(3) = 1 Then
        b = 2
    End If
    c = 3 - a - b
    Dim d As Double
        If x(1) = b Then
            d = 0
        ElseIf x(2) = b Then
            d = 1
        ElseIf x(3) = b Then
            d = 2
        End If
i = 0
For i = 1 To 3 Step 1
    If i = d Then
        res(i) = GEM(x(i), 2 - y(i))
    Else
        res(i) = GEM(a, y(i))
    End If
Next i
End If
Get1_GEM = res
End Function


text:
Q: ming32-make.exe incorrect parsing of -I and -L flags I'm on a Windows machine and use MinGW, attempting to compile a hello world program that uses a shared library. After an absurd amount of attempts, I found out the following:

*

*Manually compiling it with gcc and providing -I and -L flags for the required directories works fine.

*Using the msys make.exe file provided under the MinGW/msys/1.0/bin installation directory properly executes a Makefile with no problems

*Using the mingw32-make.exe provided under MinGW/bin doesn't work properly when trying to build using the same Makefile. From my understanding, it doesn't parse the -I and -L flags at all. It works fine if I add the dependencies (both includes and libs) under their respective MinGW directories.

These past few days while I was trying and familiarizing myself with these tools (I'm comfortable with C's syntax but know about nothing past that) I read many guides and no one seemed to have this issue (from the few that actually attempted this on a Windows machine without using an IDE). Did I miss something? Is my MinGW installation known to have this issue?
Note that at first I was attempting to compile the project using the 64-bit version of the library but failed. I'm guessing this means that I have a 32-bit MinGW installation.
Knowing that some will ask to see the Makefile:
CC = gcc
MY_LIB = -L/e/C_Projects/Libraries/MySharedLib/lib -lMyLibName
MY_INCLUDE = -I/e/C_Projects/Libraries/MySharedLib/include
CFLAGS = -Wall -c $(MY_INCLUDE)
LDFLAGS = -lmingw32 -mwindows $(MY_LIB)
EXE = Test.exe

all: $(EXE)

$(EXE): main.o

    $(CC) $< $(LDFLAGS) -o $@

main.o: main.c

    $(CC) $(CFLAGS) $< -o $@

clean:

    del *.o && del $(EXE)

The error produced by mingw32-make.exe is the following
main.c:1:22: fatal error: MyLib.h: No such file or directory
 #include <MyLib.h>
                      ^
compilation terminated.
Makefile:19: recipe for target 'main.o' failed
mingw32-make: *** [main.o] Error 1


text:
Q: RemoteConnection to SQL server2008 express failed on Visual Studio After 2 Days of search i still didnt find an answer.
Situation:
Server:
SQL Server 2008 Express installed on RemoteServer
TCP/IP: Enabled on port 1433
Named Pipes: Enabled
Database: ConDB.mdf (attached to server)
Workstation:
Microsoft Management Studio: Connection to database works

Servertype: Databasemodul
  Servername: MTTC5020\SQLEXPRESS,1433
   Authentifcation: SQL
  Server-Authentification  Username:
  testuser Password: 1234

Visual Studio 2010 Express:

Error on Database Explorer: SQL
  Network Interfaces, error: 26 - Error
  Locating Server/Instance
  Specified

Same Error Through Connection via Appconfig and connectionstring:
<connectionStrings>
    <add name="ContainerDB.My.MySettings.ConDBConnectionString" connectionString="Data Source=MTTC5020\SQLEXPRESS,1433;Initial Catalog=ConDB.mdf;User ID=testuser;Password=1234;Integrated Security=false"
        providerName="System.Data.SqlClient.SqlConnection" />
</connectionStrings>

I also tried many other connectionstrings (Via IP / AttachedDBFileName / etc.)

I also tried everything here: MSDN   portcheck through SQLCMD -U testuser -P 1234 -S MTTC5020\SQLEXPRESS,1433 works aswell  Any suggestions?

A: I now found the issue.
The connectionstring for the dbml is not only stored in the .config file.
checkout the workaround for this at:
LINQ to SQL Connection Strings

A: Because by default express editions are installed as named instances, SQL Server on the remote machine needs to be allowed in firewall, not only the port, but the service, because named instances probably will change the port from time to time. Check this post, hope this helps blogs.msdn.com/b/sqlexpress/


text:
Q: How to prevent SSL urls from leaking info? I was using google SSL search (https:www.google.com) with the expectation that my search would be private. However, my search for 'toasters' produced this query:
    https://encrypted.google.com/search?hl=en&source=hp&q=toasters&aq=f
As you can see, my employer can still log this and see what the search was. How can I make sure that when someone searches on my site using SSL (using custom google search) their search terms isn't made visible.

A: The URL is sent over SSL. Of course a user can see the URL in their own browser, but it isn't visible as it transits the network. Your employer can't log it unless they are the other end of the SSL connection. If your employer creates a CA certificate and installs it in your browser, they could use a proxy to spoof Google host names, but otherwise, the traffic is secure.

A: HTTPS protects the entire HTTP exchange, including the URL, so the only thing someone intercepting network traffic will be able to determine is that there was communication between the browser and your site (or Google in this case).  Even without the innards, that information can be useful.
Unless you have full administrative control over the systems making the queries, you should assume that anything transpiring on them can be intercepted or logged.  Browsers typically store history and cache pages in files on the local disk which can be read by administrators.  You also can't verify that the browser itself hasn't been recompiled with code to log sites that were visited, even in "private" mode.

A: Presumably your employer provides you with a PC, the software on it, the LAN connection to its own corporate network, the internet proxy and corporate firewall, maybe DNS servers, etc etc.
So you are exposed to traffic sniffing and tracing at many different levels.  Even if you browse to a url over SSL TLS, you have to assume that the contents of your http session can be recorded.  Do you always check that the cert in your browser is from google and not your employer's proxy?  Do you know what software sits between your browser and your network card, etc.
However, if you had complete control over the client, then you could be sure that no-one external to your https conversation with google would be able to see the url you are requesting.
Google still knows what you're up to, but that's a private matter between your search engine and your conscience ;)

A: to add to what @erickson said, read this. SSL will protect the data between the connected parties. If you need to hide that link from the boss then disable the browser caching of the sites visited, i.e. disable or delete the history data.


text:
Q: Airflow 2.0 errors when creating users via CLI We are getting spun up with Airflow 2.0 but are running into a weird issue when creating the initial admin user. The installation of Airflow and running airflow db init appear to run fine, but when we run the command airflow users create -u <username> --use-random-password -f <firstname> -l <lastname> -r Admin -e <emailaddress> we get the error listed below repeated about 50 times:
[2021-01-27 20:42:13,801] {base.py:593} ERROR - Add Permission on View Error: 'NoneType' object has no attribute 'permissions'
[2021-01-27 20:42:14,261] {base.py:600} ERROR - 'NoneType' object has no attribute 'permissions'
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/flask_appbuilder/base.py", line 598, in _add_permissions_menu
    self.sm.add_permissions_menu(name)
  File "/usr/local/lib/python3.7/dist-packages/flask_appbuilder/security/manager.py", line 1241, in add_permissions_menu
    self.add_permission_role(role_admin, pv)
  File "/usr/local/lib/python3.7/dist-packages/flask_appbuilder/security/sqla/manager.py", line 594, in add_permission_role
    if perm_view and perm_view not in role.permissions:
AttributeError: 'NoneType' object has no attribute 'permissions'

We haven't been able to find any documentation so we're really not sure what to do. Any suggestions would be greatly appreciated.

A: Our issue was that we weren't setting the webconfig ldap settings correctly in the shell we were running the create command.


text:
Q: SetState not updating variable within a Text widget I am having an issue where for a stateful calculator widget i'm attempting to create (BMIState); I'm unable to see the result of the calculation after calling the calculate() method.
The expected behaviour is that the Text widget that calls result.toString(), will display the calculation result based on the inputs from the two text controllers.
However, even after calling calculate() and changing the value of the result using setState(), the Text widget is still returning 'result' as a toString of its initialized value (which is null).
import 'package:flutter/material.dart';

class BMIPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => BMIState();
}

class BMIState extends State {
  TextEditingController mController = TextEditingController();
  TextEditingController kgController = TextEditingController();
  double result = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
            child: ListView(
              children: <Widget>[
                Column(
                  children: <Widget>[
                    TextField(
                      controller: mController,
                      keyboardType: TextInputType.number,
                      ),
                    ),
                        child: TextField(
                          controller: kgController,
                          keyboardType: TextInputType.number,),
                       ),
                    FlatButton(
                      onPressed: () {
                        calculate();
                      },
                    ),
                    Column(
                      children: <Widget>[
                        Text(
                          "BMI",
                          style: TextStyle(
                              fontSize: 40, fontWeight: FontWeight.w600, color: Colors.orangeAccent),
                        ),
                        Text(
                          result.toString(),
                          style: TextStyle(
                              fontSize: 40, fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ],
              ],
            )));
  }
  void calculate() {
    double height = double.tryParse(mController.text);
    double weight = double.tryParse(kgController.text);

    setState(() {
      result = weight ~/ height * height;
    });
  }
}

A: You can copy paste run full code below
Step 1: You need to use class BMIState extends State<BMIPage> { not class BMIState extends State {
Step 2: Scaffold body not child
working demo

full code
import 'package:flutter/material.dart';

class BMIPage extends StatefulWidget {
  @override
  BMIState createState() => BMIState();
}

class BMIState extends State<BMIPage> {
  TextEditingController mController = TextEditingController();
  TextEditingController kgController = TextEditingController();
  double result = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView(children: <Widget>[
      Column(
        children: <Widget>[
          TextField(
            controller: mController,
            keyboardType: TextInputType.number,
          ),
          TextField(
            controller: kgController,
            keyboardType: TextInputType.number,
          ),
          FlatButton(
            child: Text("calculate"),
            onPressed: () {
              calculate();
            },
          ),
          Column(
            children: <Widget>[
              Text(
                "BMI",
                style: TextStyle(
                    fontSize: 40,
                    fontWeight: FontWeight.w600,
                    color: Colors.orangeAccent),
              ),
              Text(
                result.toString(),
                style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
              ),
            ],
          ),
        ],
      )
    ]));
  }

  void calculate() {
    double height = double.tryParse(mController.text);
    double weight = double.tryParse(kgController.text);

    print(mController.text);
    print(kgController.text);
    setState(() {
      result = weight ~/ height * height;
    });

    print(result);
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: BMIPage(),
    );
  }
}


text:
Q: SELECT Records from the last time a record was recorded using SQL I have this table where I enter sales by customer name and date
So I have two fields where I select the customer name and Date, Then I make a sales.
Everything is fine until I tried to add a feature when you select the customer name. I want the last time he or she made a sale to show the total amount of the sale.
Already the total amount is recorded at the time of entry and stored in another column in the table.
Now my problem is with the date.
Let's just say the last time, that particular customer made a sale was on the 20th March. And he or she is now making a sale on the 24th March which is today.
I want to query out the sales amount he or she made on the 20th March.
As I already said, I have the total sales amount stored in the table already so I could just use
SELECT CustomerName, totalAmount
FROM transactions
WHERE DATE(created_at) = DATE(NOW() - INTERVAL 1 DAY);

But with this method, it's referring me to 24th march which is not what I want.
Can someone guide me on how to accomplish this?
As the query will have to find the last date the customer made the sale and bring forward the total sales amount.
Thank you all.

A: You can do that by simple limit and order by
   SELECT CustomerName, totalAmount FROM transactions WHERE CustomerName = $CustomerName order by created_at desc limit 1,1

A: You can make use of subquery
  SELECT CustomerName, totalAmount
  (select  top 1 DATE(created_at)  FROM transactions a where
   a.CustomerName= b.CustomerName) lastSaleDate
  FROM transactions b
  where  CustomerName= $customer


text:
Q: Simple syntax for bringing a list element to the front in python? I have an array with a set of elements.  I'd like to bring a given element to the front but otherwise leave the order unchanged.  Do folks have suggestions as to the cleanest syntax for this?
This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N operation could do.
    mylist = sorted(mylist,
                    key=lambda x: x == targetvalue,
                    reverse=True)

A: To bring (for example) the 6th element to the front, use:
mylist.insert(0, mylist.pop(5))

(python uses the standard 0 based indexing)

A: This requires just two list operations (no index):

mylist.remove(targetvalue)
mylist.insert(0, targetvalue)

A: I would go with:
mylist.insert(0, mylist.pop(mylist.index(targetvalue)))

A: Note: the following code (and the sample code you offered) will put all matching elements at the front.
x = targetvalue
for i in range(len(mylist)):
    if(mylist[i] == x):
        mylist = [mylist[i]] + mylist[:i] + mylist[i+1:]

For example, if mylist = [1, 2, 3, 4, 3] and x = 3, this will result in [3, 3, 1, 2, 4].


text:
Q: Including war dependencies with "mvn jetty:run" I've a war project that includes other war dependencies as "overlays". I can run the project using "mvn jetty:run-exploded".
However, if i try with "mvn jetty:run", it will not work (stuff expected from dependent war is not found). It does not take the war dependencies (specified in pom.xml) into consideration.
My understanding is that "mvn jetty:run" uses src directory as web resources.
Q: Any way to make "mvn jetty:run" take war dependencies into considerations automatically?
I am trying to find the fastest way to develop with maven jetty plugin, jetty:run-exploded can be a bit slow even with -DskipTests.


text:
Q: jupyter is showing callable error in dict function dicts=dict([("first",1), ("second",2)])
dicts
-------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-ced152e9bd1a> in <module>
----> 1 dicts=dict([("first",1), ("second",2)])
      2 dicts

TypeError: 'dict' object is not callable
--------------------------------------------------


text:
Q: May I create a dataframe from a set in Pandas? relations = []
...
rel_dict = {'start': start, 'end': end, 'type': relationship}
if rel_dict not in relations:
    relations.append(rel_dict)

rel_df = pd.DataFrame(relations)

This is the code I am creating a dataframe, and the following slows down a lot:
if rel_dict not in relations

If I define 'relations' as a set, can DataFrame take a set to create a dataframe? If I also want to keep the order in the set, can I do it?
Or maybe I should define 'relations' as a dict:
from collections import OrderedDict
relations = OrderedDict()
...
if rel_dict not in relations:
    relations[rel_dict] =  rel_dict

What's your suggestion?

A: Two ideas:
First, use frozendict, which is like a python dict but hashable (and immutable). Pandas dataframe constructor does not mind taking set of frozen dicts, so this will work:
relations = set()
...
rel_dict = frozendict(start=start, end=end, type=relationship)
relations.add(rel_dict)

rel_df = pd.DataFrame(relations)

This will loose the ordering, so to keep it we can replace the set by dict (you are using python 3.6 or later, right?)
relations = dict()
...
rel_dict = frozendict(start=start, end=end, type=relationship)
relations[rel_dict] = None

rel_df = pd.DataFrame(relations.keys())

Second, feed the whole thing to pandas and deduplicate after
df = pd.DataFrame(rel_dicts).drop_duplicates(keep='first')

Not sure which one is faster, you will have to try.


text:
Q: Cannot connect with Cisco VPN but can connect with ShrewSoft VPN EDIT: We connected an air card to the computer to use a different Internet connection and using the Cisco software, we were able to successfully connect to our VPN server. I just don't understand why the ShrewSoft VPN client would connect but the Cisco connection won't.
I'm not our network admin so sorry if I butcher some of the terminology.
I have a computer at remote site that connects to our network through Cisco VPN. It uses the Cisco VPN software to do so. The problem is that the computer at this site cannot connect to our VPN because it is getting error "Reason 412: The remote peer is no longer responding."
Cisco Reason 412 http://dl.dropbox.com/u/35257/cisco-error.png
To see if perhaps something on their network was blocking the connection, I installed the ShrewSoft VPN client on the computer, imported our .pcf file and connected with no problem. I have tried two different versions of the Cisco VPN software (4.8.0.* and 5.0.03.*) and have the same problem.
I installed Wireshark on the computer and have confirmed (while trying to connect through Cisco) that the computer is trying to contact the VPN server but is not receiving a response.
Wireshark packets http://dl.dropbox.com/u/35257/wireshark-vpn.png
We are not having any other problems regarding users not being able to connect. I'm at a loss at what else to check. I'll be monitoring this and have access to the computer at any time.

A: Have you tried going into your connection profile and changing the transport to IPSec over TCP instead of IPSec over UDP? that fixes a lot of weird issues like that for me.


text:
Q: Time conversion Not working properly? I am using the ionic time picker in my project. When I select the time picker it passes a value to the controller. For example when I select 09:00pm, the console shows 79200. If I select 07:00pm the console shows 68400. I want to convert the value to 12 hrs format. I have followed some steps, but it's not working for me.
My code:
var a = new Date($scope.timePickerObject12Hour.inputEpochTime*1000);
console.log(a);
var b = moment.utc(a).format("HH:mm");
console.log(b)
$scope.timePickerObject12Hour.inputEpochTime = val;
console.log(val);
//var yourDateObject = new Date();

var selectedTime = new Date();
var amPmHour = $filter('date')(selectedTime, 'hh');
console.log(amPmHour);
$scope.time = $filter('date')(new Date(val*1000), 'hh:mma');
console.log($scope.time);
console.log('Selected epoch is : ', val, 'and the time is ', selectedTime.getUTCHours(), ':', selectedTime.getUTCMinutes(), 'in UTC');

I tried the code above, but nothing is working. Below i have added my origional code:
$scope.timePickerObject12Hour.inputEpochTime = val;
    console.log(val);
    console.log('Selected epoch is : ', val, 'and the time is ', selectedTime.getUTCHours(), ':', selectedTime.getUTCMinutes(), 'in UTC');

*

*on the first console.log i am getting 68400,

*for second  console log I am getting 68400 and the time is  19:00 in UTC. How to convert 12 hr format for the selected time?

A: You can receive your 12Hrs format by using the modulo operator:
var hours = new Date(68400000).getHours();    // 20 o'clock in milliseconds
hours = hours % 12;                           // Division by 12
hours = hours ? hours : 12;                   // the hour '0' should be '12'
console.log(hours)                            // 8

A: I assume you want the result as a string. Here is a simple implementation with moment.js:
var secs = 68400;
console.log(moment().startOf('day').add(secs, 'seconds').format("h:mm a"));

Will output "7:00 pm"
See in plunker http://plnkr.co/edit/D0ai2PpEhnuJkTYblW29?p=preview

A: var secs = 68400;
console.log(moment().startOf('day').add(secs, 'seconds').format("hh:mma"));

See i outputed as 07:00pm! So 07:00pm is called 12 hour clock


text:
Q: CKEditor: Submenu (drop downlist) not appearing I need a drop down submenu list within the drop down menu list in plugin. but problem is, that menu shows that It has drop down submenu list but contents of list are not being loaded. empty submenu is shown.
Snap shot:

code :
CKEDITOR.plugins.add( 'microdata',
{
   requires : [ 'styles', 'button' ],
   init : function( editor )
    {
        var  markup= editor.config.languages,
                items = {};
        for ( var i = 0 ; i < markup.length ; i++ )
        {
            var parts = markup[i].split( '=' );
            var name= parts[1].split('org/');
            items[ parts[ 0 ] ] =
                {
                    label : parts[ 0 ],
                    group : 'microdata',
                    icon: this.path + 'icon1.png' ,
                    order : i,
                    getItems: function()
                        {
                            var selection = editor.getSelection();
                            return {
                                name: CKEDITOR.TRISTATE_OFF,
                                friend: CKEDITOR.TRISTATE_OFF
                            };
                        }

        };
             var  name=
                {
                  label: 'name',
                  group: 'microdata',
                  //command: 'nameCmd',
                  order: 5
                }
        editor.addMenuGroup( 'microdata' );
        editor.addMenuItems( items,name);/*,
                friend:
                {
                  label: 'friend',
                  group: 'microdata',
                  //command: 'friendCmd',
                  order: 10
                }
                );*/
        editor.ui.add( 'Microdata', CKEDITOR.UI_MENUBUTTON,
        {
            label: 'Microdata',
            command: 'Microdata',
            modes : { wysiwyg:1 },
            className : 'cke_button_microdata',
            icon: this.path + 'icon1.png' ,
                    onMenu : function()
                {
                    var activeItems = {};

                    for ( var prop in items )
                    {
                        if ( items.hasOwnProperty( prop ) )
                            activeItems[ prop ] = CKEDITOR.TRISTATE_ON;
                    }

                    return  activeItems;
                }
        } );
      }
} );
CKEDITOR.config.languages = [ 'Place=http://schema.org/Place'];

Commands are not added yet.
Any help is greatly appreciated.


text:
Q: Generic type polymorphism confusion? I have an abstract factory like so:
public abstract class DAOFactory {
    public abstract EntryDAO<EntryDTO> getEntryDAO();
    ...
}

With my DAO and DTO interfaces like so:
public interface EntryDTO extends GenericDTO {
}

public interface EntryDAO<T extends EntryDTO> extends GenericDAO<T, Serializable> {
}

And my implementation like so:
public class EntryDTOImpl implements EntryDTO {
}

public class EntryDAOImpl<T extends EntryDTO> extends GenericDaoImpl<EntryDTOImpl, ObjectId>
 implements EntryDAO<T> {
}

Now, if I create a factory and override the getEntryDAO method like so:
public class MyDAOFactory extends DAOFactory {
    @Override
    public EntryDAO<EntryDTO> getEntryDAO() {
        try {
            return new EntryDAOImpl<EntryDTOImpl>();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

I get a compile time error:

Type mismatch: cannot convert from EntryDAOImpl to EntryDAO

EDIT
I've updated my abstract factory like so:
public abstract <T extends EntryDTO> EntryDAO<T> getEntryDAO();

And made the change in my factory implementation:
@Override
public <T extends EntryDTO> EntryDAO<T> getEntryDAO() {
    try {
        return new EntryDAOImpl<EntryDTOImpl>();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Now I'm getting the compile time error:

Type mismatch: cannot convert from EntryDAOImpl<EntryDTOImpl> to EntryDao<T>

A: Define the abstract method this way (notice ? instead of T):
public abstract EntryDAO<? extends EntryDTO> getEntryDAO(); //should work for you

I recreated the scenario the way I understood it: returning subclass1<subclass2> as interface1<interface2>
For example, this works well:
public static List<? extends CharSequence> dostuff1() {
    return new ArrayList<String>();
}

But this doesn't work:
public <B extends CharSequence> List<B> dostuff2() {
    return new ArrayList<String>();
}

This gives the same compile-time error that you got: Type mismatch: cannot convert from ArrayList<String> to List<B>

A: The reason this is happening is that you're trying to return an EntryDaoImpl<EntryDTOImpl>, which is a subtype of  EntryDao<EntryDTOImpl>, but not of EntryDao<EntryDTO>, which is the return type of the method.
Solution:
I believe you want to change the return type of the getEntryDao method to
EntryDAO<? extends EntryDTO>.

A: Just change the return type from EntryDao<T> to EntryDao<? extends T>. That will do the trick:
@Override
public <T extends EntryDto> EntryDao<? extends T> getEntryDao() {
    try {
        return new EntryDAOImpl<EntryDTOImpl>();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return dao;
}

Now as a justification, suppose EntryDao<T> has methods that return T like
T load(Serializable id);

and methods that accept T like
void save(T t);

Now assume PersonDTO extends EntryDTO, and  CarDTO extends EntryDTO.
If EntryDao<EntryDTO> were assignable from EntryDao<EntryDTOImpl>, it would also be assignable form EntryDao<PersonDTO> and  EntryDao<CarDTO>.
Then you could do:
EntryDao<EntryDTO> x = new EntryDao<PersonDTO>();       // currently this is a compile time error

If that were legal, you could do:
x.save(new CarDTO());   // a run time error, because x can only save Persons, not Cars

But what is EntryDao<? extends EntryDTO>? It is just EntryDao with all T-accepting methods like save(T) removed.


text:
Q: Detect overflow when overflow set to hidden I have an interesting problem.
Background: I have a simple header. A logo and two links are floated on the left side, while two drop down menu links are floated on the right, all contained in a header div that i 100% width. If I shrink the screen horizontally enough the two drop down menu links dropped below the left-floated elements (of course). After doing some research I decided to use overflow: hidden on the parent header div so that the two drop-down menus would disappear instead of dropping to the next line. This solution works great in my situation. However, I found that the drop-down menu layer was cut off below the header because of the overflow:hidden solution. Just for reference, my drop down menu was created using simple javascript that toggles between css classes to get the drop down effect. I simply added a line to the function onclick events in the javascript that when a menu link is clicked on, overflow changes from overflow:hidden to overflow: none (and of course toggles back to hidden when the menu is unclicked), which works great because there is supposed to never be overflow if the menu buttons are visible (they disappear and are hidden when there is overflow,).
Problem: If a user opens a menu (aka clicks on a drop down menu link) and THEN shrinks the horizontal scrollbar without first closing the menu, the header has an overflow that is still set to none because the user hasn't toggled the header back to hidden because the menu is still open. Thus, my original problem of the two menu links dropping beneath the floated left divs again. Working with what I'm already doing, I'm trying to come up with some kind of onchange() event in the header that will detect when there is overflow, even though overflow is set to hidden. Any thoughts?
Relevant CSS Code:
.level1raise { //header class
background: #F8F8F8;
margin: 0px;
border-bottom: 1px solid #BCD2EE;
height: 55px;
overflow: hidden;
}
.level1drop { //alternate header class
background: #F8F8F8;
margin: 0px;
border-bottom: 1px solid #BCD2EE;
height: 55px;
overflow: none;
}

Sample of Javascript that toggles menu:
function supportdrop() {

if (document.getElementById("support").className == "hidesupportmenu") {
document.getElementById("support").className = "showsupportmenu";
document.getElementById("supportdrop").className = "supportmenuheadclicked";
document.getElementById("supportarrow").className = "uparrowimage";
document.getElementById("help").className = "hidehelpmenu";
document.getElementById("helpdrop").className = "helpmenuhead";
document.getElementById("helparrow").className = "downarrowimage"; //^THESE DEAL WITH MENU
document.getElementById("level1").className = "level1drop"; //THIS IS THE HEADER TOGGLE
} else if (document.getElementById("support").className == "showsupportmenu") {
document.getElementById("support").className = "hidesupportmenu";
document.getElementById("supportdrop").className = "supportmenuhead";
document.getElementById("supportarrow").className = "downarrowimage"; //^MENU
document.getElementById("level1").className = "level1raise"; //HEADER TOGGLE
}

}

If you need me to post more code I will, but I think what I've included kind of shows what I'm doing, let me know otherwise. I'd post an attempted solution, but I'm not really sure what solution to attempt. I'm trying to avoid JQuery. Thanks!

A: I came up with a solution for any others who are attempting a similar path. Because (1) I use 100% width of the page and the page is dynamic I can disable the horizontal scrollbar and (2) the width of the elements inside the header don't change so I can add up the minimum-required width before the drop down menu links drop to the next line, I can use the following solution:
HTML:
<body onresize="checkwidth()">

Javascript:
function checkwidth() {

var currentwidth = window.innerWidth || document.documentElement.clientWidth ||
document.body.clientWidth;

if (currentwidth < 770) {

 document.getElementById("level1").className = "level1raise";
document.getElementById("help").className = "hidehelpmenu";
document.getElementById("helpdrop").className = "helpmenuhead";
document.getElementById("helparrow").className = "downarrowimage";
 document.getElementById("support").className = "hidesupportmenu";
document.getElementById("supportdrop").className = "supportmenuhead";
 document.getElementById("supportarrow").className = "downarrowimage";

 } else {

 document.getElementById("level1").className = "level1drop";

 }

}

Works beautifully and is cross-browser. A little crude, but oh well.


text:
Q: when exactly django query execution occures In a technical interview a questioner asked me a weird question regarding to the execution of querysets. Suppose we have a profile model like below:
class Profile(models.Model):
    user = models.OneToOneField('User').select_related(User)
    surname = models.TextField(null=True)

q = Profile.object.all()
or
q = Profile.object.get(id=1)

l = q.filter(active=True)

he asked how many query execution has been happened and I replied as the python interpreter executes Profile.object.all() at the begging then one query is already done. However, he answered zero, and one if we call the query, something like this:
for a in l:
   a.surname

Is his answer true in django?
another doubt was about models.OneToOneField('User'), why he didn't use django.contrib.auth.models.User and defined models.OneToOneField('User').select_related(User)

A: QuerySets are not evaluated until you do something that actually needs them to be evaluated. As the documentation for the class itself states a QuerySet:

Represent a lazy database lookup for a set of objects.

Emphasis on the word lazy. This is because one often needs to call or chain methods on a queryset, a good example being a group by requiring subsequent calls to .values() and .annotate(). If a queryset was evaluated directly then we would be making too many unneeded queries to the database, slowing down execution to a halt.
As to when exactly a queryset is evaluated I would list the answer in short (for the long answer refer to When QuerySets are evaluated [Django docs]):

*

*Iterating a queryset

*Slicing a queryset (with the step parameter)

*Pickling/Caching a queryset

*Calling repr(), len(), list(), or bool() on a queryset

*Various methods like get(), first(), last(), latest(), or earliest(), etc. also make a query to the database


text:
Q: Does Yosemite Upgrade Destroy Bootcamp? I use Mavericks with Bootcamp on my iMac.
If I upgrade Yosemite via AppStore, what happens to Bootcamp?
Can I start it as usual or will the Bootcamp partition become unusable?

A: Bootcamp is not affected by an upgrade from Mavericks to Yosemite.


text:
Q: For Loop Quitting Prematurely Here's my loop
-(void)analyzeDataWithSearchTerm:(NSString *)searchTerm {

    [searchResults removeAllObjects];

    NSLog(@"number of items = %i", [itemIDRows count]);

    for (int i = 0; i < [itemIDRows count]; i++) {

        bool foundResult = FALSE;
        if ([[[itemIDRows objectAtIndex:i] lowercaseString] rangeOfString:[searchTerm lowercaseString]].location != NSNotFound) {
            NSLog(@"ID matches %@", [itemIDRows objectAtIndex:i]);
            foundResult = TRUE;
        }
        if ([[[itemNameRows objectAtIndex:i] lowercaseString] rangeOfString:[searchTerm lowercaseString]].location != NSNotFound) {
            NSLog(@"name Matches %@", [itemNameRows objectAtIndex:i]);
            foundResult = TRUE;
        }
        if ([[[barcodeRows objectAtIndex:i] lowercaseString] rangeOfString:[searchTerm lowercaseString]].location != NSNotFound) {
            NSLog(@"barcode Matches %@", [barcodeRows objectAtIndex:i]);
            foundResult = TRUE;
        }
        if ([aliasRows objectAtIndex:i] != [NSNull null]) {
            if ([[[aliasRows objectAtIndex:i] lowercaseString] rangeOfString:[searchTerm lowercaseString]].location != NSNotFound) {
                NSLog(@"alias Matches %@", [aliasRows objectAtIndex:i]);
                foundResult = TRUE;
            }
        }

        if (foundResult) {
            NSNumber *result = [NSNumber numberWithInt:i];
            NSLog(@"found result");
            [searchResults addObject:result];

        } else {
            NSLog(@"no result was found this time");
        }
    }

    if (isScanning) {
    //do something different
    }
}

The problem seems to occur if I have set "isScanning" to true (it's a bool) and run the method "analyzeDataWithSearchTerm" a second time.
Basically this loop checks if the item is already in a purchase order. If not the item is offered to be added. Next time the item is scanned the loop runs and goes through and should detect the item as being in the purchase order. I've setup break points but the second time the loop runs (only 2 items in the order) it finds one result, gets to the line foundResult = TRUE, doesn't set the bool to true, and the whole method just stops. It never even makes it to
if (foundResult) { }
Any ideas why this might be happening?

A:
The problem seems to occur if I have set "isScanning" to true (it's a
  bool) and run the method "analyzeDataWithSearchTerm" a second time.

It would be helpful if you could confirm that this is when the problem occurs, and not just that it seems to be when it occurs. Presuming that is the case, the piece of code we most need to see is whatever is inside this:
if (isScanning) {
//do something different
}

The most logical conclusion is that something in the "do something different" is changing the conditions that would otherwise be examined in your loop, such as perhaps removing objects from itemIDRows (which I presume is an NSArray or NSMutableArray) or causing that NSArray/NSMutableArray object to be released.
Your use of != NSNotFound seems like a strange test to me and is likely the cause of your problems. You could meet this criteria if there was another error other than NSNotFound—but could for example then stall on [itemIDRows objectAtIndex:i]. If you change your logic to matching the two strings, rather than failing to not match, I suspect your error will either disappear or the resulting problem elsewhere will more clearly highlight the problem.


text:
Q: jQuery: is there a reason not to always use live() for click and other functions? I really like using .live() in jQuery for click() focus() blur() and other interaction events.
I do a lot of prototyping, so I find it gives me great flexibility if I want to dynamically add elements. For that reason, I find myself drawn to the idea of using it by default all the time. Is this a good idea, or is this bad performance?
Does using .live('click',function(){}) slow things down in a way that .click(function(){}) doesn't?

A: I think following answer will be suitable for the performance impact it does create How does jQuery .live() work?

A: Regarding the performance, using the live is better in most cases. However live has several pitfalls, which are described in the documentation here http://api.jquery.com/live/#caveats.

A: I remember that .live uses event bubbling.
In my experience, I've seen noticeable performance hit using .live in big document with a frequently triggered event like mouseover.
jQuery Doc:

But as of jQuery 1.4, event bubbling can optionally stop at a DOM
  element "context".

So, you can use that to minimize the performance effect.

A: If you don't need your events to bubble up to the top of the DOM and you know the context in which your event will occur then delegate() is a much better choice in terms of performance.  See this stackoverflow post on why delegate() is better than live() in this regards.


text:
Q: Nunit 3: Test a Controller that uses IHttpClientFactory as Constructor Parameter Update 20221024: I have used Ruikai Feng's solution in order to use Mockoon with my tests. I realize this is not a correct approach from a unit testing approach and am working to change my approach.
Update 20221019: I have been using moq to mock out the IHttpClientFactory. The reason why I wanted to instantiate it was to call mock apis created in a tool called Mockoon which replicates apis. I have been so far unable to call these APIs likely because I have not yet properly mocked the ihttpclientfactory. I appreciate all the feedback as the solution is still ongoing at this time.
I am using a .NET 6 Web API controller with IHttpClientFactory to perform external API calls. As such, I have the following constructor:
public MyController(IHttpClientFactory httpClientFactory)
{
  _httpClientFactory = httpClientFactory;
}

This works because in my Program.cs I add an HTTP Client to my builder.Services.
In my tests, how do I instantiate/set up the httpClientFactory for the controller because I need it to instantiate my controller: var controller = new MyController(httpClientFactory); generates an error since there isn't any settings added.
I ran into a similar issue with configurations from appsettings.json and resolved with ConfigurationBuilder but there doesn't seem to be a similar one for IHttpClientFactory.
If you need any more information, please let me know. Thanks!

A: In order to be able to use a properly mocked IHttpClientFactory in your unit test you need to do the following steps:
Setup a DelegatingHandler mock
var mockHandler = new Mock<DelegatingHandler>();
mockHandler.Protected()
    .Setup<Task<HttpResponseMessage>>("SendAsync", It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>())
    .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK))
    .Verifiable();
mockHandler.As<IDisposable>().Setup(s => s.Dispose());

This sample mock will always return with 200 OK status code and without a response body

*

*Tailor the setup for your needs

Create an HttpClient
var httpClient = new HttpClient(mockHandler.Object);

It creates an HttpClient instance and pass the above handler to it
Setup an IHttpClientFactory mock
var mockFactory = new Mock<IHttpClientFactory>(MockBehavior.Strict);
mockFactory
  .Setup(factory => factory.CreateClient())
  .Returns(httpClient)
  .Verifiable();

It setups an IHttpClientFactory mock to return the above HttpClient for the CreateClient method call

*

*If you use the IHttpClientFactory to create a named client then change the Setup to this .Setup(factory => factory.CreateClient(It.IsAny<string>()))
Use the mock objects for verification
mockFactory.Verify(factory => factory.CreateClient(), Times.Once);
mockHandler.Protected()
   .Verify("SendAsync", Times.Once(), It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>());

A: I tried as below:
[TestFixture]
    public class IndexActionTests
    {
        private HomeController controller;

        [SetUp]
        public void Setup()
        {
            var services = new ServiceCollection();
            services.AddHttpClient();
            var provider = services.BuildServiceProvider();
            var httpclientfactory = provider.GetService<IHttpClientFactory>();
            controller = new HomeController(httpclientfactory);
        }

        [Test]
        public void Test1()
        {
            var result = controller.Index();
            Assert.AreEqual(typeof(ViewResult),result.GetType());
        }
    }

Result:


text:
Q: There is an error in my stored procedure I have a problem with my stored procedure
ALTER PROCEDURE [dbo].[TIGER_CREATE_RUNTIME_TABLE](@NOMBRE_TABLA varchar(100))
AS
    DECLARE @SQLQUERY1 AS NVARCHAR(600)
BEGIN
    SET @SQLQUERY1 = 'CREATE TABLE '+@NOMBRE_TABLA + '(
    SEGMENTO varchar(200) NULL,
    TCNFOL varchar(200) NOT NULL,
    TCCOPL_A varchar(200) NULL,
    ID_LIN_NEG varchar(200) NULL,
    TIP_LIN varchar(200) NULL,
    MON_ID_MONEDA varchar(200) NULL,
    LINEAS_FACT varchar(200) NULL,
    CF_VOZ varchar(200) NULL,
    CF_DATOS varchar(200) NULL,
    ADIC_MINS varchar(200) NULL,
    ADIC_LDN varchar(200) NULL,
    ADIC_LDI varchar(200) NULL,
    ADIC_SMS varchar(200) NULL,
    PAQ_SMS varchar(200) NULL,
    ADIC_DATOS varchar(200) NULL,
    OTROS varchar(200) NULL,
    SUB_TOT varchar(200) NULL,
    PERIODO_ANALISIS varchar(200) NULL,
    PERIODO_ALTA varchar(200) NULL,
    CATEGORIA varchar(200) NULL,
    RUC varchar(200) NULL)'

    EXEC sp_ExecuteSql @SQLQUERY1
END

As you can see, I'm using dynamic SQL, but there is an error while I execute it.

Mens. 102, Level 15, State 1, Line 20
  Incorrect syntax near 'varch'.

Is there any wrong with dynamic SQL? Thanks for a while.

A: I would change your @sqlquery1 to varchar(max), I think you are hitting the character limit when you add your table name:
 DECLARE @SQLQUERY1 AS NVARCHAR(max)

You have your limit of your query string set to 600 but when you add in a table name of up to varchar(100) you are most likely going over the limit.
If you run just the following with no table name the len is 726 characters:
DECLARE @SQLQUERY1 AS NVARCHAR(max)

SET @SQLQUERY1 = 'CREATE TABLE (
    SEGMENTO varchar(200) NULL,
    TCNFOL varchar(200) NOT NULL,
    TCCOPL_A varchar(200) NULL,
    ID_LIN_NEG varchar(200) NULL,
    TIP_LIN varchar(200) NULL,
    MON_ID_MONEDA varchar(200) NULL,
    LINEAS_FACT varchar(200) NULL,
    CF_VOZ varchar(200) NULL,
    CF_DATOS varchar(200) NULL,
    ADIC_MINS varchar(200) NULL,
    ADIC_LDN varchar(200) NULL,
    ADIC_LDI varchar(200) NULL,
    ADIC_SMS varchar(200) NULL,
    PAQ_SMS varchar(200) NULL,
    ADIC_DATOS varchar(200) NULL,
    OTROS varchar(200) NULL,
    SUB_TOT varchar(200) NULL,
    PERIODO_ANALISIS varchar(200) NULL,
    PERIODO_ALTA varchar(200) NULL,
    CATEGORIA varchar(200) NULL,
    RUC varchar(200) NULL)'

select LEN(@sqlquery1)

If you leave your query string at a length of 600 your create table statement will be cut off and will generate an error.


text:
Q: Why won't this Java OpenGL (JOGL) program run? The following code was taken from https://sites.google.com/site/justinscsstuff/jogl-tutorial-2
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.opengl.*;
import javax.media.opengl.awt.GLCanvas;

public class SimpleScene {
    public static void main(String[] args) {
        GLProfile glp = GLProfile.getDefault();
        GLCapabilities caps = new GLCapabilities(glp);
        GLCanvas canvas = new GLCanvas(caps);

        Frame frame = new Frame("AWT Window Test");
        frame.setSize(300, 300);
        frame.add(canvas);
        frame.setVisible(true);

        // by default, an AWT Frame doesn't do anything when you click
        // the close button; this bit of code will terminate the program when
        // the window is asked to close
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

It compiles without any problems, but when I use
java SimpleScene

I get the following error
C:\Users\Mitc\Drive\Google Drive\Game\Display>java SimpleScene
Exception in thread "main" java.lang.NoClassDefFoundError: javax/media/opengl/GLCapabilitiesImmutable
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.getMainMethod(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: javax.media.opengl.GLCapabilitiesImmutable
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 6 more

Any ideas as to what is going wrong?

A: As you have already compiled the file with JOGL jar files, you just need to make sure that you have these files in your classpath at runtime:
java -cp gluegen-rt.jar;jogl-all.jar;. SimpleScene

A: You need to use JOGL < v2.3 because the package names changed. Here's a link to the v2.2.4 jars. For some reason gluegen-rt.jar and jogl-all.jar were actually zip files which contained the real jars, so keep that in mind.
I realize this isn't the correct answer given when the OP originally posted, but I encountered the same error and thought I'd help out the next person.


text:
Q: How to get in array data from table? I have a tags_ids array 1,3,2 and
data in my table:
+---------+----------+
| user_id | tag_id   |
+---------+----------+
|       1 |        1 |
|       1 |        2 |
|       2 |        1 |
|       2 |        2 |
+---------+----------+

I want to get the users ids into array, but not working:
foreach ($tags_ids as $i)
    {
        if ($result = $mysqli->prepare("SELECT `user_id` FROM `mytable` WHERE `tag_id`=?"))
        {
            $result->bind_param("i",$i);
            $result->execute();
            $result->bind_result($d);
            $result->fetch();
            $result->close();
        }

        if (!in_array($d,$users_ids)) $users_ids[] = $d;
    }

My result is always 1. Whats I'm doing wrong, and can I do it in a more simple way?

A: you need a while loop, you can find it here for full assist:http://www.youtube.com/watch?v=hO0YOOeJrOE
be sure to watch the other video's too, very helpfull.
goodluck,
PHPNoob


text:
Q: Is it possible to delete chrome history using wildcards? I know I can highlight individual items in chrome's history and remove them, using chrome:history, but I'd like to delete all entries from a given domain, and all entries matching a given set of search criteria.  How would I do that?  Is there an extension that gives this?

A: Get the Better History extension, it does all that.

A: *

*Do your search like normal

*Click on "Edit Items"

*To delete all of the entries for that screen, check the first item you want to delete and scroll to the bottom. Now hold down the Shift key on your keyboard and click the last item shown. All items are now checked and you can remove individual items as you see fit.

*Now click "Remove selected"

*Click "Older" at the bottom of the page

*Repeat steps 3-4

*Click on "Done removing items"
Source: Google Groups

A: No, unfortunately there is currently no way to efficiently remove multiple entries from the history, however I have submitted an issue to request a way to remove multiple entries via wildcard and/or date range. Time will tell if they ever bother to implement it.


text:
Q: Installing Epson XP-424 wireless printer I tried to install an Epson XP-424 wireless printer on my Ubuntu 14.04 system.
Originally, I attempted to add it directly from "Printers" in "System Settings". This specific model is not listed, so I tried the generic 9-pin driver and then the generic 24-pin driver. I got the same result either way, which is that, it appears installed, but when I send a job to the printer, it spits out nothing but blank paper.
I was able to install the Epson app on my iPhone, and I can print from my phone, so I know there is no problem with the hardware, the ink levels, etc.
I am sort of stuck. Any suggestions?

A: There is a specific driver for your printer.  They are available on the Epson website  To use them you will need to install a specific package as mentioned in the Epson downloads:
sudo apt-get install lsb
The specific package that you need to download depends on your version of Ubuntu. If you are running a 32 bit Ubuntu, download epson-inkjet-printer-escpr_1.6.2-1lsb3.2_i386.deb
And if you are running 64 bit Ubuntu, download epson-inkjet-printer-escpr_1.6.2-1lsb3.2_amd64.deb
These files can be opened using the Ubuntu Software Center by double-clicking on them, or installed from the command line by the command
sudo dpkg -i epson-inkjet-printer-escpr_1.6.2-1lsb3.2_amd64.deb


text:
Q: How to change audio track in played movie which is streamed to Apple TV via VLC local sharing? I setup the VLC app on Apple TV following this tutorial and I can stream movies from my Macbook Pro to Apple TV. The only thing I don't know how to change is audio track. The movies has multiple audio tracks and it seems VLC can play only the default.
How can I change the audio track in this setup?

A: I've found it. One have to swipe down on Apple TV's remote and the menu for audio tracks and subtitles will appear.


text:
Q: Moveto not working while drawing path in svg I am creating an flag icon inside a svg and my code is
createSVG('path', {
            d:`M ${this.x},${this.y+this.height} ${this.x+6},${this.y+this.height} ${this.x+3},${this.y+this.height} ${this.x+3},${this.y} ${this.x+this.width-3},${this.y} ${this.x+this.width-3},${this.y+(this.height/2)} ${this.x+3},${this.y+(this.height/2)} M ${this.x+5} ${this.y+10} Z`,
            stroke: 'rgb(239, 86, 117)',
            'stroke-width': 2,
            fill: 'none',
            class: 'checkpoint',
            append_to: this.shape_group
        });

where this.x and this.y are coordinates
the createSVG function is defined as follows
function createSVG(tag, attrs) {
    const elem = document.createElementNS('http://www.w3.org/2000/svg', tag);
    for (let attr in attrs) {
        if (attr === 'append_to') {
            const parent = attrs.append_to;
            parent.appendChild(elem);
        } else if (attr === 'innerHTML') {
            elem.innerHTML = attrs.innerHTML;
        } else {
            elem.setAttribute(attr, attrs[attr]);
        }
    }
    return elem;
}

Above is the flag that I got

But Iam supposed to draw this

The thing is that Iam unable to move the start point to the center for the drawing the tick
d:`M ${this.x},${this.y+this.height} .......${this.y+(this.height/2)} Z M ${this.x+5} ${this.y+10} Z`,

I tried using M but its not working. Please help me out with this.
Thanks in advance


text:
Q: Text input wraps onto 2 lines Im seeing some strange behavior on my text inputs, they are wrapping on to 2 lines when the text is too long.
They have padding and are 100% width. If I remove either of these 2 CSS rules the text stops wrapping.
I cant put my actual site live and when I try and recreate the issue (eg with jsfiddle) I cant recreate it. Here are screen shots from my iPhone:

What could be causing this? This is not default behavior but the padding and 100% width are required from my design, so I need to find another way of preventing the wrapping.
UPDATE As I said I cant recreate the issue. My attempt is below. Ive used chrome dev tools to copy all the CSS rules, and the html is the same, however the result does not wrap.
http://codepen.io/anon/pen/uHCav

<input placeholder="Middle name" type="text" maxlength="40" name="middle" id="edit-middle" size="60" value="" >

.cont {
  background: grey;
  width: 300px;
  margin-left: 100px
}
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
input {

  border-left-color: #e35235 !important;

}
input {
  border-left-style: solid;
border-left-color: #c9d8e6;
border-left-width: 6px !important;
font-size: 1.2em;
border-top: none !important;
border-bottom: none !important;
border-right: none !important;
}
input {
  background: white;
}
input {
  padding: 15px 37px 15px 14px;
}
input {
  margin: 0;
border: none;
outline: none;
}
input {
  width: 100%;
-webkit-appearance: none;
appearance: none;
-moz-border-radius: 0;
-webkit-border-radius: 0;
border-radius: 0;
background-color: transparent;
}
input {
  font-weight: 300;
}
input {
  -webkit-text-fill-color: #19465e;
}
input {
  color: #19465e;
}

.one {
  margin-left: -20px;
margin-right: -20px;
}

A: You might have a word-break property that your input is inheriting. Try adding word-break: normal; to the input.

A: Start by paring back your document.
Create a new (blank) page with just the basics
<!DOCTYPE html>

  <title>My page title</title>

            <input placeholder="Middle name" type="text" maxlength="40" name="middle" id="edit-middle" size="60" value="" >

Simplify your inputs CSS, just the basics
input {
    font-size:1.2em;
    background:#DDD;
    padding:15px 37px 15px 14px;
    border:none;
    outline:none;
    width:100%;
}

You will notice the input will not wrap and you still have width: 100%; and padding.
Add the rest of your document one bit at a time:

*

*Javascript - check that there is no problem with input

*The rest of your CSS - check that there is no problem with input

*Any remaining styles for your input - check that there is no problem with input

*Any missing HTML - check that there is no problem with input

Put the jigsaw back together one piece at a time and clean up your code as you go.

A: Replace the width:100% to position:absolute; left:0; right:0; if you need a quick and dirty fix for this.  Just ensure that your container div then has the appropriate rules.
As a side note, it's really bad practice to have all those input rules in separate style blocks.  Try consolidating those into one, if possible.

A: Usually this kind of issues are related to the box-sizing context. You can try to define a border context for your input to ignore the padding calculation:
input {
  box-sizing: border-box;
}


text:
Q: Reasons to choose SP-Initiated or IDP-Initiated SSO In my understanding of SP-init and IDP-init SSO is as follow:
IDP-init SSO: A base64-encoded saml response is generated by IDP and send to SP, SP then verifies the response and finally the user is logged into the application if the response is valid.
SP-init SSO: A saml request is sent from SP to IDP, then IDP will authenticate the user then send back the saml response, the next part is same as IDP-init SSO.
How do we decide to choose whether the SSO is using SP-init or IDP-init ? SP-init seems to be more secure and reliable than IDP-init SSO because of the authentication part.

A: You choose based on the desired or required navigation flow of a user (assuming browser POST binding based on your description).
If your requirements dictate the user start from secure (logged in) website A and navigate without password to site B, this is by definition IdP initiated.
If on the other hand the user is expected to be on an unauthenticated site yet log in with credentials from a partner site, this is where the SP initiated scenario comes into play. StackOverflow itself offers this style of sign in if you choose to log in with a Google account (though an alternative to SAML is used). The user starts somewhere on StackOverflow, clicks the login link, chooses their IdP (in SAML semantics) as Google, and are sent with an authn request to the IdP. After credential challenge of unspecified sort (eg your browser might already have an authenticated session at the IdP site, or the IdP might use two factor auth, etc) the user is returned to the SP site with a SAML response document.

A: To me, the business requirements of the service provider's application tell you:
If all user interaction with the service provider's application will start at a "homepage", or default landing page, then IdP-initiated probably makes a lot of sense (less to break - no signed AuthnRequest needed).
If there are "deeplinks" that are provided to your users to things like reports via email (that is, a user can click on a link that should take them deep within the service provider's application), then SP-initiated is the only way forward.
In both instances, the user will be authenticated at the IdP based on the IdP's authentication rules - neither SP-init or IdP-init is "more secure" in that regard. The flows:
IdP-init:

*

*User clicks link to start IdP-init SSO

*IdP validates that User is authenticated - if not redirect for authentication

*IdP converts authentication attributes (like username, email, etc.) into SAML assertion and redirects user to SP

*SP converts SAML assertion to SP application token and redirects to application

SP-Init:

*

*User clicks link to go to SP application

*SP Application determines the user does not have a token and redirects to SP

*SP redirects to IdP

*IdP validates that User is authenticated - if not redirect for authentication

*IdP converts authentication attributes (like username, email, etc.) into SAML assertion and redirects user to SP

*SP converts SAML assertion to SP application token and redirects to application

The only difference, as you can see, is the first three steps.

A: SP-initialized  is always to prefer. IDP-initilized will make work easier for the SP implementation but it comes with a buch of problems such as XSRF, interaoperability and deep linking.


text:
Q: How do I group by month from date in SQL? I tried using month and extract functions and all of them produce an error I have a question involving these two tables:
marketing_campaign
| date    | campaign  | spend |
| ------- | ------    | ----- |
| 3/1/2020|   X       |  200  |
| 3/1/2020|   Y       |  200  |
| 3/2/2020|   X       |  200  |
| 3/2/2020|   X       |  200  |
| 3/3/2020|   Y       |  200  |

new_customers
| date    | campaign  | customer_id |
| ------- | ------    | ----------- |
| 3/1/2021|   X       |      1      |
| 3/1/2021|   X       |      2      |
| 3/2/2021|   X       |      3      |
| 3/2/2021|   X       |      4      |
| 3/2/2021|   Y       |      5      |
| 3/3/2021|   X       |      6      |
| 3/3/2021|   Y       |      7      |
| 3/3/2021|   Y       |      8      |

I needed to create a table from these two that would show spending, number of new customers and cost per customer grouped by date and campaign, and I have this query:
SELECT *, spending/signups AS cost
FROM
   (SELECT n.date, n.campaign,
    (SELECT SUM(m.spend) FROM marketing_campaign AS m WHERE m.date = n.date AND m.campaign = n.campaign) AS spending,
    COUNT(n.customer_id) AS signups
FROM new_customers AS n
GROUP BY n.date, n.campaign) AS tab1;

This query seems to be working correctly but now I need to group by months as well. I've tried doing:
SELECT *, spending/signups AS cost
FROM
   (SELECT month(n.date), n.campaign,
    (SELECT SUM(m.spend) FROM marketing_campaign AS m WHERE m.date = n.date AND m.campaign = n.campaign) AS spending,
    COUNT(n.customer_id) AS signups
FROM new_customers AS n
GROUP BY month(n.date), n.campaign) AS tab1;

And:
SELECT *, spending/signups AS cost
FROM
   (SELECT extract(month, n.date), n.campaign,
    (SELECT SUM(m.spend) FROM marketing_campaign AS m WHERE m.date = n.date AND m.campaign = n.campaign) AS spending,
    COUNT(n.customer_id) AS signups
FROM new_customers AS n
GROUP BY extract(month, n.date), n.campaign) AS tab1;

But the both produce error 1055: Expression #3 of SELECT list is not in GROUP BY clause and contains non-aggregated column. 'database_2.n.date' which is not functionally dependent on columns in GROUP BY clause.  I'm not too sure how to get the months out of the date otherwise and would appreciate any suggestions!


text:
Q: How to read solidity function with tuple data in ether-js When I call the getLandById function in remix it gives the desired result as you can see in the screenshot
Screeshot of remix IDE to get landIdbyId
When I call the same function using ether js. it will gives the output like this :
[ '0.007062190', '-0.01878356', '\x00\x00', [Getter] ]

Instead of
[ '0.007062190', '-0.01878356', '-0.019048060716011,0.007015231577652,-0.018794627684582,0.007386060761845,-0.018423798497481,0.007132627732498,-0.018677231528875,0.006761798548127,-0.019048060716011,0.007015231577652']

I'm struggling to understand how to get the data. Any idea on what should I do to get the desired result? An example would be great.
Ether-js code:
let customHttpProvider = new ethers.providers.JsonRpcProvider(API_URL);
const contract = new ethers.Contract(
  Contract_Address,
  contractAbi,
  customHttpProvider
);

//Calling readOnly Method
async function getLand() {
  const getLandById = await contract.getLandById("502");

  console.log("Land-Info", getLandById);
}

getLand();

Contract ABIs:
{
        "inputs": [
            {
                "internalType": "uint256",
                "name": "landId",
                "type": "uint256"
            }
        ],
        "name": "getLandById",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            },
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            },
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            },
            {
                "components": [
                    {
                        "internalType": "string",
                        "name": "longitude",
                        "type": "string"
                    },
                    {
                        "internalType": "string",
                        "name": "latitude",
                        "type": "string"
                    }
                ],
                "internalType": "struct LandContract.PolygonCoordinates[]",
                "name": "",
                "type": "tuple[]"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },

Solidity code:
function getLandById(uint landId)
        public
        view
        returns (
            string memory,
            string memory,
            PolygonCoordinates[] memory
        )
    {
        if (!_exists(landId)) {
            revert IdNotExist();
        }

        PolygonCoordinates[] memory coordinates = new PolygonCoordinates[](
            land[landId].polygonCoordinates.length
        );

        for (uint i = 0; i < land[landId].polygonCoordinates.length; ) {
            coordinates[i].longitude = land[landId]
                .polygonCoordinates[i]
                .longitude;
            coordinates[i].latitude = land[landId]
                .polygonCoordinates[i]
                .latitude;

            unchecked {
                i++;
            }
        }

        return (land[landId].longitude, land[landId].latitude, coordinates);
    }

A: The contract ABI defines 4 output values but your solidity code getLandById() returns only 3 values.


text:
Q: how to limit post content in wordpress blog I want to limit the content of post on wordpress blog home. So after specific amount of words content should be limited and there would be a link saying Read More..
Plz guide me how it can be done in php wordpress theme

A: There is a tag in the WordPress editor which you can use to specify the cutoff point on a blog/page excerpt.
You just have to click this button where you want the cutoff to happen

Then within your template, you just need to add the first parameter to the_content() and it will show the content up till that cutoff. If the parameter is not set, it will show all the content.
For example:
the_content('Show more...'); // shows content till the cutoff then shows the text supplied

the content(); //shows all the content

Read more about the more tag here: http://codex.wordpress.org/Customizing_the_Read_More


text:
Q: Eu tenho que entrega essa pergunta e eu já tentei e não consegui responder. Sobre Vetor

*Crie um vetor de 10 posições e digite números inteiros aleatoriamente. Depois digite um número e caso ele esteja no vetor, guarde a posição dele para mostrar ao final do programa. Senão mostre a mensagem ao final do programa "NÚMERO NÃO ENCONTRADO".

A: Se eu ainda me lembro algo de visualg é assim
    algoritmo
    var
numerodesejado : inteiro
posicaodesejada : inteiro
i: inteiro
    numeros: vetor[1..10] de inteiro
    inicio
    posicaodesejada <- 0
    numerodesejado <-10
    vetor[1] <-5
    vetor[2] <-10
    vetor[3] <-15
    vetor[4] <- 20
    vetor[5] <- 25
    vetor[6] <-30
    vetor[7] <-35
    vetor[8] <-40
    vetor[9] <-45
    vetor[10] <-50
      para i de 1 ate 10  faca
        se vetor[i]= numerodesejado entao
         posicaodesejada <- i

        fimse
      fimpara
    se posicaodesejada > 0 entao
    escreval ("A posição desejada é ", posicaodesejada)
    senao
    escreval ("POSICAO NÃO ENCONTRADA!")
    fimse

    fimalgoritmo


text:
Q: Show text box when checkbox clicked and keep showing after page reload I have written a JavaScript function that shows a text input field when a checkbox is clicked. The essence of the function is basically to change the text box display property from "none", to "block" on checkbox click. This works fine, and thus when I check the box I see the text field, and when I uncheck the box, the text box hides.
Now, I am trying to figure out how to keep the text box showing after the page is refreshed. This is where I am stuck.
Any suggestions? Thanks!
Please let me know if I need to clarify anything!

A: Best way is to store your state in a cookie and read it after load to get back to the same state : Set cookie and get cookie with JavaScript


text:
Q: setting crontab remotely using shell script. I am trying to write a code which will setup an crontab remotely using shell script. But I am facing issue with echo command as its not able to substitute variables.
Actual Code
#! /usr/bin/ksh
#! /bin/bash
clear

echo -n "" > error.out
echo -n "" > scripts_dir.out
echo -n "" > crontab_check.out

export ORACLE_SID=REPTEST
export ORACLE_HOME=/opt/app/oracle/product/11.2.0_tipical
export PATH=$PATH:$ORACLE_HOME/bin
export TNS_ADMIN=/home/oracle/NIKHIL/apex_oracle_version_changes
export SCRIPTS_DIR=/home/oracle/NIKHIL/Migration_tech_refersh
export REP_USER=repository
export EMAIL_ID="nikhil.mehta@neustar.biz"
export DAY=`date +"%m-%d-%Y"`
export HOSTNAME=$1
export SID=$2
export USAGE=$3
export ROLE=$4

create_crontab_entries() {

    echo -n "" > ${SCRIPTS_DIR}/crontab_remote_entries/crontab_remote_file_${H_NOFQDN}.${SID}
    echo
    echo -e "Creating crontab entries for RMAN backups and alert_log script"
    echo
    mv ${SCRIPTS_DIR}/crontab_remote_entries/crontab_remote_file_${H_NOFQDN}.${SID} ${SCRIPTS_DIR}/crontab_remote_entries/crontab_remote_file_${H_NOFQDN}.${SID}_$DAY
    echo -e "(crontab -l 2>/dev/null;echo "0,5,10,15,20,25,30,35,40,45,50,55 * * * * /home/oracle/SCRIPTS/MONITOR/alert_log/ksh/CHECK_LOG_ERRORS.ksh ${SID} > /tmp/check_log_${SID}.log 2>&1") |  crontab - " >> ${SCRIPTS_DIR}/crontab_remote_entries/crontab_remote_file_${H_NOFQDN}.${SID}

    echo -e "Checking if crontab is enabled for oracle user"
    ssh -o 'PreferredAuthentications=publickey' oracle@${HOSTNAME} "crontab -l" >> crontab_check.out 2>&1

    if [ "$?" = "0" ]; then
            echo
            echo -e "Crontab is enabled for Oracle user.. Creating Crontab entries!!!"
            scp  -o 'PreferredAuthentications=publickey' ${SCRIPTS_DIR}/crontab_remote_entries/crontab_remote_file_${H_NOFQDN}.${SID} oracle@${HOSTNAME}:/home/oracle >> crontab_check.out 2>&1
            ssh -o 'PreferredAuthentications=publickey' oracle@${HOSTNAME} "chmod 777 /home/oracle/crontab_remote_file_${H_NOFQDN}.${SID};/home/oracle/crontab_remote_file_${H_NOFQDN}.${SID};rm -f /home/oracle/crontab_remote_file_${H_NOFQDN}.${SID}" >> crontab_check.out 2>&1

Problamatic echo Command
echo -e "(crontab -l 2>/dev/null;echo "0,5,10,15,20,25,30,35,40,45,50,55 * * * * /home/oracle/SCRIPTS/MONITOR/alert_log/ksh/CHECK_LOG_ERRORS.ksh ${SID} > /tmp/check_log_${SID}.log 2>&1") |  crontab - " >> ${SCRIPTS_DIR}/crontab_remote_entries/crontab_remote_file_${H_NOFQDN}.${SID}

Errors encountered while running script
Migration_tech_refersh_post_check.ksh: line 275: 1) |  crontab - : ambiguous redirect

Please help with the echo command which will substitute variables as expected.

A: I was able to resolve the issue by separating the whole command into 3 strings as below.
    str1='(crontab -l 2>/dev/null;echo "0,5,10,15,20,25,30,35,40,45,50,55 * * * * /home/oracle/SCRIPTS/MONITOR/alert_log/ksh/CHECK_LOG_ERRORS.ksh '
    str2="$str1 $SID > /tmp/check_log_${SID}.log 2>&1"
    str3='") |  crontab - '
    full_cmd1="$str2$str3"

Thanks everyone for your help.
Regards,
Lancerique.


text:
Q: Check if T in Func delegate is null before invoking? I am trying to figure out how to check if an object is null before it is invoked. Here is some sample code:
 public class NotifyTemplate<T> where T : class
    {
        public Func<T, string> Value { get; set; }
        public string Key { get; set; }
    }

    public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }

        public Contact Contact { get; set; }

    }

    public class Contact
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

I want check if any of the objects i am trying to invoke are null before I actually invoke the delegate. I can throw a try catch, but that seems overkill. Here is an example of my usage:
var notifyList = new List<NotifyTemplate<User>>()
            {
                new NotifyTemplate<User>()
                {
                    Value = u => u.Contact.FirstName,
                    Key = "FName"
                },
                new NotifyTemplate<User>()
                {
                    Value = u => u.UserName,
                    Key = "UserName"
                }
            };

            var user = new User()
            {
                Id = 1,
                UserName = "ddivita@dd.com",

            };

            foreach (var notifyTemplate in notifyList)
            {
               //This is where I want to check if the value is null or not before I invoke.

                var name =  notifyTemplate.Value.Invoke(user);
            }

As you can see the Contact object is null and not initialized in the new User declaration. So, inside the foreach statement I want to inspect the Value property and see if the object inside my delegate is null before I invoke it.
The whole point to this is that we are setting up a notification system and to make it easier on the developer, the Func will be used to replace keys inside a notification template.
Here is what teh temaplte might look like:
<html>
   <body>
      Hello There [FName] [LName]. Thank you for signing up using the username: [UserName].

   </body>
</html>

The developer will pass into our notification service what template they want to use and the list of NotifyTemplate
If for some reason the contact information was not persisted correctly and we pull a User object from the database, let's assume the Contact object is null. We need to evaluate that the Contact object is null before we call invoke to get the value.

A: You could do this in the lambda:
Value = u => u.Contact != null ? u.Contact.FirstName : string.Empty

A: As Neolisk suggested, I am doing this:
foreach (var notifyTemplate in notifyList)
            {
                var value = string.Empty;
                try
                {
                   value  = notifyTemplate.Value.Invoke(user);
                }
                catch (Exception ex)
                {

                    //log error
                }

                var theVlaue = value;
        }


text:
Q: Build endpoints using struct I'm building a struct with constants to form URL endpoints.
struct Constants {
    struct Api {
        static let BaseUrl = "http://srv.com/ws_rest/"
        static let LoginPassword1 = "credentials?member_account_pwd="
        static let LoginUsername2 = "&member_account_login="
        static let Login3 = "&channelId=4"
    }
}

The final result is:
let url = URL.baseUrlWith(string: Constants.Api.LoginPassword1 + "pass" + Constants.Api.LoginUsername2 + "user" + Constants.Api.Login3)

This is only for one endpoint. Does anyone knows of a better pratical aproach to this?

A: it might be useful to have a function that helps you
    func urlString(with baseURL: String, and parameters: [String: String])->String {
        var mutableBaseURL = baseURL
        for (i, param) in parameters.enumerated() {
            var symbol = "&"
            if i == 0 { symbol = "?" }

            mutableBaseURL += "\(symbol)\(param.key)=\(param.value)"
        }
        return mutableBaseURL
    }

So your constants would become something like
struct Constants {
    struct Endpoints {
        static let login = "http://srv.com/ws_rest/credentials"
    }

    struct Parameters {
        static let username = "member_account_login"
        static let password = "member_account_pwd"
        static let channelId = "channelId"
    }
}

Somewhere in your code you will have
let url = urlString(with: Constants.Endpoints.login, and: [
                Constants.Parameters.username: username,
                Constants.Parameters.password: pass,
                Constants.Parameters.channelId: "4"
            ])

Hope it helps.


text:
Q: How to solve the issue with "your app will not work unless you update your google play service"? I am having Google+ login in my app.I have done all the steps which was mentioned in this link here
The issue is when I run my app it shows "this app will not work unless you update your Google play service".Then I updated my google-play services to its latest version.
later I update the Google-API Intel x86 atom_64 system image under API-21.Still I find the same message to appear.
can't fix this issue need help.Don't know what I am doing wrong.

A: Check if the feature that you use really needs the latest version of google apis, you can use older versions of the google play services by adding
compile 'com.google.android.gms:play-services:6.5.87'

under dependencies in build.gradle

A: Try resetting app preferences. Settings>Apps>menu>reset app preferences. This sometimes helps with Play issues.

A: You have to import google play service from sdk->extras->google->googleplayservices->googleplayservice-lib;
Then rightclick on project -> properties ->add
add the library
to get new version go to sdkmanager->extras->googleplayservice (install or update)
if it is not available then you have to update adt tools and then it will appear.
for that use link
How can I update my ADT in Eclipse?


text:
Q: How to center align the below subfigure when it stands alone? I have three subfigures as shown in the MWE below, I want to align the subfigure c in the center below the two upper figures, how to do that?
\documentclass{scrartcl}
\usepackage{caption}
\usepackage{floatrow}
\usepackage{subcaption}
\usepackage{graphicx,xcolor}
\usepackage[framemethod=tikz]{mdframed}

\newcommand{\fakeimage}{{\fboxsep=-\fboxrule\fbox{\rule{0pt}{3cm}\hspace{4cm}}}}

\begin{document}
\begin{figure}
\begin{mdframed}[
  align=center,
  linecolor=black,
  fontcolor=black,
  backgroundcolor=white,
  userdefinedwidth=0.9\textwidth,
  roundcorner=5pt,
  skipabove=0pt,
  skipbelow=0pt,
  leftmargin=0pt,
  innerleftmargin=20pt,
  innerrightmargin=0pt,
  innertopmargin=5pt,
  innerbottommargin=5pt,
  innerlinewidth=0pt,
  middlelinewidth=0pt,
  outerlinewidth=1pt]
\floatsetup[subfigure]{captionskip=10pt}
%===================== the two upper subfigures ================
\begin{minipage}{.44\textwidth}
    \begin{subfigure}{\linewidth}
    \centering
    \fakeimage
    \caption{Image}\label{fig:image1}
    \end{subfigure}\\[0ex] %
    \qquad
\end{minipage}
\begin{minipage}{.44\textwidth}
    \begin{subfigure}{\linewidth}
    \centering
    \fakeimage
    \caption{Image}\label{fig:image12}
   \end{subfigure}
\end{minipage}%
\vfill
%===================== the one below subfigure ================
\begin{minipage}[c]{.94\textwidth}
  \centering
  \begin{subfigure}{\linewidth}
  \fakeimage
  \caption{Image}\label{fig:image3}
  \end{subfigure}
\end{minipage}%
\end{mdframed}
\RawCaption{\caption{General caption}
\label{fig:images}}
\end{figure}
\end{document}

which results in:

A: I wouldn't be using minipage at all; just subfigure is enough.
Code
\documentclass{scrartcl}
\usepackage{caption}
\usepackage{floatrow}
\usepackage{subcaption}
\usepackage{graphicx,xcolor}
\usepackage[framemethod=tikz]{mdframed}

\newcommand{\fakeimage}{{\fboxsep=-\fboxrule\fbox{\rule{0pt}{3cm}\hspace{4cm}}}}

\begin{document}
\begin{figure}
\begin{mdframed}[
  align=center,
  linecolor=black,
  fontcolor=black,
  backgroundcolor=white,
  userdefinedwidth=0.9\textwidth,
  roundcorner=5pt,
  skipabove=0pt,
  skipbelow=0pt,
  leftmargin=0pt,
  innerleftmargin=20pt,
  innerrightmargin=0pt,
  innertopmargin=5pt,
  innerbottommargin=5pt,
  innerlinewidth=0pt,
  middlelinewidth=0pt,
  outerlinewidth=1pt]
\floatsetup[subfigure]{captionskip=10pt}
%===================== the two upper subfigures ================
% \begin{minipage}{.44\textwidth}
    \begin{subfigure}{.44\linewidth}
    \centering
    \fakeimage
    \caption{Image}\label{fig:image1}
    \end{subfigure} %
    \qquad
% \end{minipage}
% \begin{minipage}{.44\textwidth}
    \begin{subfigure}{.44\linewidth}
    \centering
    \fakeimage
    \caption{Image}\label{fig:image12}
   \end{subfigure}
% \end{minipage}%
% \vfill
\\[2ex]
%===================== the one below subfigure ================
% \begin{minipage}[c]{.94\textwidth}
% \centering
  \begin{subfigure}{\linewidth}
  \centering
  \fakeimage
  \caption{Image}\label{fig:image3}
  \end{subfigure}
% \end{minipage}%
\end{mdframed}
\RawCaption{\caption{General caption}
\label{fig:images}}
\end{figure}
\end{document}

Output

A: You probably already have thought of this but i would just use tikzeditor? Its supereasy to draw stuff there and you can get everything aligned in any way you want.


text:
Q: PuTTY: Change default SSH login directory In Windows, I use PuTTY to log in a Linux-based remote server via SSH.
Is is possible to change the default directory entry point I get to after I connect and login? (That would be a nice time saver.)
e.g. from server/home/ to server/home/subdir/subdir/

A: You can also change the directory within PuTTY itself:

*

*Configuration → Connection → SSH

*Fill in the "Remote command" field with the following:
cd subdir/subdir ; /bin/bash

A: *

*Add cd subdir/subdir to ~/.bashrc or ~/.bash_profile, or

*change the home directory of the user.

A: You could use screen to keep your current directory by always logging into the same screen session.
Add the screen command with parameters to your putty saved session under SSH>Remote Command.
See the screen documentation for which parameters to use.
screen -R -O -t mysession -S mysession -f

A: Depends on a lot of things. Mainly the server operating system. Most SSH servers run Linux or Unix of some flavor. When you connect via any method of remote text login (as SSH is one member of this category) such a system will automatically spawn a shell process to talk to you. That's probably "bash", and it runs various things on startup. Check out
man bash
to learn more. One of the many things you can do is cd to a subfolder.


text:
Q: Completely format and remove a hardrive
As seen in image disk1 is paritioned in 3 parts (C,E&F) I have nothing to do with it.
All I need to do is format and remove all partitions from disk2 that is partitioned as D and other two unecessary partitions. Naturally i have to change the system folder to some other drive so explain me how.

A: *

*Right click on Computer in the start menu and select Manage

*In the left list select Disk Management

You can delete each partition , just right click on it and select delete!!


text:
Q: SPF record with DMARC policy is not picking up the policy We are now going through security verification, and we are using SecurityScorecard for it.
One of the issues that we are still trying to fight, is the SPF record.
The details of the error are as follows:
SPF softfail record without DMARC policy detected.
Now, I could, of course, set it to HardFail, but I wanted to have the policy to quarantine first. But it seems to not work.
Here are the two record that I currently have:
v=DMARC1; p=quarantine; sp=quarantine; rua=mailto:dmarc@mailinblue.com!10m; ruf=mailto:dmarc@mailinblue.com!10m; rf=afrf; pct=100; ri=86400
v=spf1 include:servers.mcsv.net include:spf.sendinblue.com mx include:_spf.google.com ~all
I was under the assumption that the DMARC record is the one setting the policy.
What am I doing wrong here?

A:
I was under the assumption that the DMARC record is the one setting the policy. What am I doing wrong here?

The DMARC policy is effective, if the recipient is capable of DMARC. Otherwise, if the recipient is only validating SPF, the SPF action is effective.
But in addition, SecurityScorecard may on top set higher requirements for consistency, even if it is not required my the DMARC/SPF standards.
Has the DMARC record been validated to be effective (i.e. correctly configured)?


text:
Q: Drupal 7: print theme from hook menu with good performance I'm working in a hook menu for a custom route, like this:
function mymodule_menu() {
  $items = [];
  $items['myroute/%'] = array(
    'page callback'     => 'my_callback',
    'page arguments'     => array(1),
    'access arguments'  => array('access content'),
  );
  return $items;
}

In the theme_hook, I added a new template feature, like this:
function mymodule_theme($existing, $type, $theme, $path) {
  $default = array(
    'path' => drupal_get_path('module', 'mymodule') . '/templates',
    'variables' => array(),
  );
  return array(
    'product_tile' => array_merge($default, array(
      'template' => 'product-tile',
    )),
  );
}

I created a template file called 'product-tile.tpl.php', which is working fine for all situations and is a partial template.
In the callback function, I need to return a specific .tpl.php template, like this:
function my_callback($parameter) {

 $template_data = 'lorem ipsum';
 $output = theme('product_tile', array('content' => $template_data ));
 echo ($output);

}

The point is: the 'theme()' function is taking too long to render data and it renders not only the template, but the whole html structure, which is not needed and is not part of the template.
Ex: template is:

But when i get my response to '/myroute/myparameter, instead of printing my template, it prints all html structure like this:

  ......lots of stuff here +js +css + all drupal stuff

And takes a lot of time to print (like 10s or more).
I tried to cache it by using cache_get and cache_set, but strange things are happening, like random empty responses.
Does anyone know a more performant way to print a partial template in a hook menu in drupal 7? It's terribly slow this way.
Thanks in advance

A: Your custom route is mapped to a page callback, a function that must return content to be rendered inside the page to deliver (not just print something).
This content can be either :

*

*an HTML string

*a drupal render array

*or a menu status code (MENU_ACCESS_DENIED, MENU_NOT_FOUND, etc.)

That content (once rendered if not an HTML string) is what you actually get in the $content or $page['content'] variable being passed to the active theme's page.tpl.php.
Now, your issue may be caused just by using this template (if it contains heavy PHP or bad implementations for example, whatever the reason), but it could be something totally different :

*

*the 'theme()' function is taking too long to render data
The time it takes to deliver that page does not necessarily mean it's caused by this theme function. You can check the time it really takes to render that specific template - not the whole HTML page - it's probably not 10 sec :
$start = microtime(true);
$output = theme('product_tile', array('content' => 'lorem ipsum'));
$end = microtime(true);
$time = $end - $start;

# dpm() is brought by devel module
dpm('product_tile rendering: ' . $time . 'sec.');

The page delivery could be long because of some heavy drupal hooks and preprocess functions involved in rendering your custom template, but it may also be the cost of rendering the other regions of the page (sidebar, header, footer, etc.).

*when I get my response to /myroute/myparameter, instead of printing my template, it prints all html :
As explained above, the response for a routed path is a full HTML page that contains as 'content' the output of the 'page callback' defined in the corresponding menu item. The expected behavior for a drupal page callback is precisely to return the content to be displayed on that page, the full HTML page is loaded. That's why a return statement is expected (don't assume anything if it's not), don't use print or echo functions in a page callback, to see what's the content of variables use debugging functions like dpm) :
function my_callback($parameter) {
  $template_data = 'lorem ipsum';
  $output = theme('product_tile', array('content' => $template_data ));

  # debug the output of 'product_tile'
  dpm($output);

  # return what should be displayed on that page
  return output;
}