text:
Q: Facebook Profile Information JSON Parsing in Android For example : if the given below is json of the person's profile on facebook got thorugh facebook sdk login through android app , How we will get the School Name fron the education Field in th json data in android . Please Help
Data :
  {
   "id": "1464730016",
   "name": "Ravi Tamada",
   "first_name": "Ravi",
   "last_name": "Tamada",
   "link": "https://www.facebook.com/ravi8x",
   "username": "ravi8x",
   "birthday": "12/22/1988",
   "hometown": {
      "id": "112158005464147",
      "name": "Baruva"
   },
   "location": {
      "id": "102186159822587",
      "name": "Chennai, Tamil Nadu"
   },
   "bio": "Author: www.androidhive.info\r\nCo-author: www.9lessons.info",
   "work": [
      {
         "employer": {
            "id": "179366562092719",
            "name": "ByteAlly"
         },
         "location": {
            "id": "102186159822587",
            "name": "Chennai, Tamil Nadu"
         },
         "position": {
            "id": "124917314217511",
            "name": "Product Head"
         }
         ]
      }
   ],
   "favorite_athletes": [
      {
         "id": "18620649907",
         "name": "Virat Kohli"
      }
   ],
   "education": [
      {
         "school": {
            "id": "131587206873093",
            "name": "Raghu Engineering College (REC)"
         },
         "degree": {
            "id": "140065339390579",
            "name": "B.Tech"
         },
         "year": {
            "id": "142963519060927",
            "name": "2010"
         },
         "type": "Graduate School",
         "classes": [
            {
               "id": "192259410803415",
               "name": "2010",
               "with": [
                  {
                     "id": "584960408",
                     "name": "Santosh Patnaik"
                  }
               ],
               "from": {
                  "id": "584960408",
                  "name": "Santosh Patnaik"
               }
            }
         ]
      }
   ],
   "gender": "male",
   "relationship_status": "Single",
   "website": "www.androidhive.info\nwww.9lessons.info\nwww.twitter.com/ravitamada\nwww.about.me/rv",
   "timezone": 5.5,
   "locale": "en_US",
   "languages": [
      {
         "id": "106059522759137",
         "name": "English"
      },
      {
         "id": "107617475934611",
         "name": "Telugu"
      },
      {
         "id": "112969428713061",
         "name": "Hindi"
      },
      {
         "id": "343306413260",
         "name": "Tamil"
      }
   ],
   "verified": true,
   "updated_time": "2012-03-02T17:04:18+0000"
}

A: JSONObject jsonResult = new JSONObject(jsonUser);
JSONArray data = jsonResult.getJSONArray("education");
 if(data != null)
    {
     for(int i = 0 ; i < data.length() ; i++)
        {
            JSONObject c = data.getJSONObject(i);
            String type = c.getString("type");
            if(type.equalsIgnoreCase("college"))
                {

                    JSONObject school = c.getJSONObject("school");
                    String id2 = school.getString("id");
                    String name2 = school.getString("name");

                    JSONObject year = c.getJSONObject("year");
                    String id_y = school.getString("id");
                    String name_y = school.getString("name");

                }

        }
    }

A: Supposing that you've this json into a jsonObject that you retrieve as response, this is the way:
// Get jsonArray 'education' from main jsonObject
JSONArray jsonArrayEducation = jsonObject.getJSONArray("education");
JSONObject jsonSchool = jsonArrayEducation.getJSONObject("school");

Note that if you are interested only at the name, you can group the two lines above into
JSONObject jsonSchool = jsonObject.getJSONArray("education").getJSONObject("school");

// get school name
String schoolName = jsonSchool.getString("name");


text:
Q: Permanently reordering fields in feature class programmatically using ArcObjects with VB.Net Would someone be able to share the logistics on how to permanently programmatically reorder fields in a feature class with ArcObjects, VB.Net.
I want to be able to do this in the geodatabase not in the IOrderedLayerFields Interface of the Carto assembly.

A: Even with ArcObjects, the only way to permanently reorder fields in a table or feature class is to drop the table completely and re-create it. There is a very popular ArcGIS Idea to get this implemented, so vote for it if you want to see such a feature.

A: This is possible in python using FeatureClasstoFeatureClass with Fieldmappings. You can also rename fields at the same time.
So if you have a Featureclass with FIELD3,FIELD2,FIELD1 and you want the result to be FIELD1,F2,F3 then the following code should accomplish this.
arcpy.env.overwriteOutput = True

input_fpath = "c:\\gis\\Geodatabases\\temp.gdb\\in_fc"

output_dpath = "c:\\gis\\Geodatabases\\temp.gdb"
output_fname = "out_fc"

fms = arcpy.FieldMappings()

fm = arcpy.FieldMap()
fm.addInputField(input_fpath,"FIELD1")
fms.addFieldMap(fm)

fm = arcpy.FieldMap()
fm.addInputField(input_fpath,"FIELD2")
of = fm.outputField
of.name = "F2"
of.aliasName = "F2"
fm.outputField = of
fms.addFieldMap(fm)

fm = arcpy.FieldMap()
fm.addInputField(input_fpath,"FIELD3")
of = fm.outputField
of.name = "F3"
of.aliasName = "F3"
fm.outputField = of
fms.addFieldMap(fm)

arcpy.conversion.FeatureClassToFeatureClass(input_fpath,output_dpath,output_fname,"",fms)

A: I know this is totally out of the scope of the question, but could be useful for those who want to reorder fields inside a table only once by hand. You can do the trick by importing the classes (or the whole geodatabase) into a personal geodatabase. Then open it with Access and reorder the fields (yeah, cool) and export it back to the original format.
Hope it helps

A: To reorder GIS fields that have like fields per feature class and table so those fields are reordered in front of all the rest of the fields.  This works on the complete dataset.  Make sure fields exist and are aliased properly.
Import Libraries
import arcpy
import sys

Declare Workspace
path="D:/temp"
dbname="/gis"
arcpy.env.workspace=path+dbname+'.gdb'
demogis=arcpy.env.workspace
newdb=path+dbname+'_New.gdb'
print(path+dbname+'.gdb')
print(demogis)
print (newdb)

Reorder Fields
Create New File Geodatabase and Feature Datasets
arcpy.management.Delete(path+dbname+'_New'+'.gdb')
arcpy.management.CreateFileGDB(path,dbname + '_New')
try:
    for ds in arcpy.ListDatasets():
        output_dpath = (path+dbname + '_New' + '.gdb')
        arcpy.CreateFeatureDataset_management(output_dpath, ds, ds)
except Exception:
    e = sys.exc_info()[1]
    print(e.args[0], ds)

Reorder Field Mapping in Feature Classes
'pfields' list needs to be updated to fields and alias field names in order.  This will set order for the fields within the feature classes.  Fields must exist in feature class.
pfields=[('AssetID','Asset Identifier'),('Display','Display Name'),('OpStatus','Operational Status'),('LifeCycleStatus','Lifecycle Status'),('Location','Location Description'),('Address','Address'),('OwnedBy','Owned By'),('MaintBy','Maintained By'),('PrimaryImage','Primary Image'),('CondInspScore','Condition Score'),('CondInspDate','Condition Date'),('WarrantyDate','Warranty Date'),('InstallDate','Install Date'),('InstallCost','Install Cost'),('ExpReplaceDate','Exp Replace Date'),('ExpReplaceCost','Exp Replace Cost'),('Age','Age'),('Criticality','Criticality'),('iPoF','Failure Probability'),('iCoF', 'Failure Consequence'),('iBRE','Business Risk'),('iMSPU','Maint Under Perform'),('iMSPO','Maint Over Perform'),('iMSR','Maint Score'),('iMCFY','Maint Curve Fast Yr'),('iMCSY','Maint Curve Slow Yr'),('iMCAY','Maint Curve Avg Yr'),('iMSName','Maint Strategy Name'),('iCalcDate','OpInsights Calc Date'),('IndFacID','Indoors Facility Identifier'),('IndLevID','Indoors Level Identifier'),('Comments','Comments')]
datasets = arcpy.ListDatasets(feature_type='feature')
datasets = [''] + datasets if datasets is not None else []
for ds in datasets:
    for fc in arcpy.ListFeatureClasses(feature_dataset=ds):
        pfield=[item[0] for item in pfields]
        palias=[item[1] for item in pfields]
        desc = arcpy.Describe(fc)
        output_dpath = (path+dbname + '_New' + '.gdb'+'/'+ds)
        input_fpath = demogis+'/'+ds+'/'+fc
        output_fname = fc
        fms = arcpy.FieldMappings()
        fcall = [(f.name,f.aliasName) for f in arcpy.ListFields(demogis+'/'+ds+'/'+fc) if f.editable]
        ffield = [item[0] for item in fcall]
        falias=[item[1] for item in fcall]
        fields2Add = list(set(fcall) - set(pfields))
        try:
            for pfield,palias in pfields:
                fm = arcpy.FieldMap()
                fm.addInputField(input_fpath,pfield)
                of = fm.outputField
                of.name = pfield
                of.aliasName = palias
                fm.outputField = of
                fms.addFieldMap(fm)
        except Exception:
            e = sys.exc_info()[1]
            print(e.args[0], fc,pfield)
        try:
            for ffield,falias in fields2Add:
                if ffield != "SHAPE" and ffield != 'Shape':
                    fm = arcpy.FieldMap()
                    fm.addInputField(input_fpath,ffield)
                    of = fm.outputField
                    of.name = ffield
                    of.aliasName = falias
                    fm.outputField = of
                    fms.addFieldMap(fm)
        except Exception:
            e = sys.exc_info()[1]
            print(e.args[0], fc,ffield)
        arcpy.conversion.FeatureClassToFeatureClass(input_fpath,output_dpath,output_fname,"",field_mapping=fms)

Reorder Field Mapping in Tables
'pfields' list needs to be updated to fields and alias field names in order.  This will set order for the fields within the tables.  Fields must exist in tables.
pfields=[('AssetID','Asset Identifier'),('Display','Display Name'),('OpStatus','Operational Status'),('LifeCycleStatus','Lifecycle Status'),('Location','Location Description'),('Address','Address'),('OwnedBy','Owned By'),('MaintBy','Maintained By'),('PrimaryImage','Primary Image'),('CondInspScore','Condition Score'),('CondInspDate','Condition Date'),('WarrantyDate','Warranty Date'),('InstallDate','Install Date'),('InstallCost','Install Cost'),('ExpReplaceDate','Exp Replace Date'),('ExpReplaceCost','Exp Replace Cost'),('Age','Age'),('Criticality','Criticality'),('iPoF','Failure Probability'),('iCoF','Failure Consequence'),('iBRE','Business Risk'),('iMSPU','Maint Under Perform'),('iMSPO','Maint Over Perform'),('iMSR','Maint Score'),('iMCFY','Maint Curve Fast Yr'),('iMCSY','Maint Curve Slow Yr'),('iMCAY','Maint Curve Avg Yr'),('iMSName','Maint Strategy Name'),('iCalcDate','OpInsights Calc Date'),('IndFacID','Indoors Facility Identifier'),('IndLevID','Indoors Level Identifier'),('Comments','Comments')]
tables = arcpy.ListTables()
for tb in tables:
    output_dpath = (path+dbname + '_New' + '.gdb')
    input_fpath = demogis+'/'+tb
    pfield=[item[0] for item in pfields]
    palias=[item[1] for item in pfields]
    output_fname = tb
    fms = arcpy.FieldMappings()
    fcall = [(f.name,f.aliasName) for f in arcpy.ListFields(demogis+'/'+tb) if f.editable]
    ffield = [item[0] for item in fcall]
    falias=[item[1] for item in fcall]
    fields2Add = list(set(fcall) - set(pfields))
    try:
        for pfield,palias in pfields:
            fm = arcpy.FieldMap()
            fm.addInputField(input_fpath,pfield)
            of = fm.outputField
            of.name = pfield
            of.aliasName = palias
            fm.outputField = of
            fms.addFieldMap(fm)
    except Exception:
        e = sys.exc_info()[1]
        print(e.args[0], tb,pfield)
    try:
        for ffield,falias in fields2Add:
            if ffield != "SHAPE" and ffield != 'Shape':
                fm = arcpy.FieldMap()
                fm.addInputField(input_fpath,ffield)
                of = fm.outputField
                of.name = ffield
                of.aliasName = falias
                fm.outputField = of
                fms.addFieldMap(fm)
    except Exception:
        e = sys.exc_info()[1]
        print(e.args[0], tb,ffield)
    arcpy.conversion.TableToTable(input_fpath,output_dpath,output_fname,"",field_mapping=fms)

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to edit some Row height in tableview I have 15 rows in tableview this table are dynamic table but I want row 5 and 11 to height 20(This is a topic menu in slide menu). I edit in story board but it doesn't change.

A: Just put the conditions over here :
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 5){
         return 20;
    }
    else{
         return 71.0;
    }
}

A: Implement heightForRowAtIndexPath delegate.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath      *)indexPath;
{
   CGFloat rowHeight = 10.0;

   if(0 == indexPath.section && (5 == indexPath.row || 11 == indexPath.row))
   {
      rowHeight = 20.0;
   }

   return rowHeight;
}

A: You should set default height in storyboard(which is more likely to be used) and if you want to return different heights for each cell than you should use the below delegate method of UITableView and incorporate the conditions for returning the height of UITableViewCell's based on your requirement(in your case the requirement is to return the height of row 5th and 11th as 20 else for other rows some height, lets assume 50). You can do so as -
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 5 || indexPath.row == 11)
         return 20.0;
    else
         return 50.0;
}


text:
Q: how to capture the keydown event of the AVPlayer? I'm writing a video player using the AVkit under macOS, the AVPlayer can response to the keyboard event, for example, space key down to pause/play the video, left arrow key down to move back the video.
I want to capture the keydown event, so that I can do more controls to the AVPlayer, how to do it?
the following is my sample code:
import SwiftUI
import AVKit
import AVFoundation

public class VideoItem: ObservableObject {
    @Published var player: AVPlayer = AVPlayer()
    @Published var playerItem: AVPlayerItem?

    func open(_ url: URL) {
        let asset = AVAsset(url: url)

        let playerItem = AVPlayerItem(asset: asset)
        self.playerItem = playerItem

        player.replaceCurrentItem(with: playerItem)

    }
}

public struct PlayerView: NSViewRepresentable {
    @Binding var player: AVPlayer

    var titles:[Title] = []
    public init(player:Binding<AVPlayer>,currentSeconds:Binding<Double>,subtitleFile:Binding<String>,currentTitle:Binding<Title?>)
    {
        self._player = player

    }

    public func updateNSView(_ NSView: NSView, context: NSViewRepresentableContext<PlayerView>) {
        guard let view = NSView as? AVPlayerView else {
            debugPrint("unexpected view")
            return
        }
      //  status = player.timeControlStatus.rawValue

        view.player = player

    }

    public func makeNSView(context: Context) -> NSView {
        let av = AVPlayerView(frame: .zero)

        return av
    }

}

A: I'v got a solution, to capture the keydown event, We can create a subclass from AVPlayerView and override it's keydown event.


text:
Q: How to allow or disallow bitwise operations I'm looking for a certain type that allows perfomring flag / bitwise operations with other type but not with itself.
Imagine the following scenario:
public enum Suit : byte
{
    Spades      = 0x00, // bits: xx00 xxxx
    Hearts      = 0x10, // bits: xx01 xxxx
    Diamonds    = 0x20, // bits: xx10 xxxx
    Clubs       = 0x30  // bits: xx11 xxxx
}

public enum Rank : byte
{
    Ace         = 0x01, // bits: xxxx 0001
    _2          = 0x02, // bits: xxxx 0010
    //  ...
    _10         = 0x0A, // bits: xxxx 1010
    Jack        = 0x0B, // bits: xxxx 1011
    Queen       = 0x0C, // bits: xxxx 1100
    King        = 0x0D  // bits: xxxx 1101
}

I'd like to allow the following operation:
playingCardQueenOfHearts = Suit.Hearts| Rank.Queen;

But not the followings:
thisIsNonsenseInMyScenario = Suit.Spades | Suit.Hearts;
thisIsOdd = Rank.Jack | Rank.Ace;

Probably the enum isn't the best choice (in fact: it allows just the opposie I'm looking for). Is there any other type, or some way to archieve what I'm looking for?

I know I could cast to perform it (queenOfHearts = (byte)Suit.Hearts| (byte)Rank.Queen), but
a. Casting allows anything:
thisIsWhat = (int)Suit.Spades | (int)DayOfWeek.Sunday;

b. I'd like to restrict, or at least make difficult OR-ing elements of the same type:
thisIsNonsenseInMyScenario = Suit.Spades | Suit.Hearts;
thisIsOdd = Rank.Jack | Rank.Ace;

A: I'd make a type (it could be a class or a struct) for this, e.g.
public struct Card
{
    public Suit Suit { get; private set; }
    public Rank Rank { get; private set; }
    public Card(Suit suit, Rank rank)
        : this()
    {
        this.Suit = suit;
        this.Rank = rank;
    }
    // include implementations for GetHashCode, Equals, ==, and !=
}

Use like
Card queenOfHearts = new Card(Suit.Hearts, Rank.Queen);


text:
Q: Count frequency and plot I would need to plot the frequency of items by date. My csv contains three columns: one for Date, one for Name & Surname and another one for Birthday.
I am interested in plotting the frequency of people recorded in a date. My expected output would be:
         Date  Count
0   01/01/2018      9
1   01/02/2018     12
2   01/03/2018      6
3   01/04/2018      4
4   01/05/2018      5
..         ...    ...
..  02/27/2020    122
..  02/28/2020     84

The table above was found as follows:
by_date = df.groupby(df['Date']).size().reset_index(name='Count')

Date is a column in my csv file, but not Count. This explains the reason why I am having difficulties to draw a line plot.
How can I plot the frequency as a list of numbers/column?

A: Although not absolutely required, you should convert the Date column into Timestamp for easier analysis in later steps:
df['Date'] = pd.to_datetime(df['Date'])

Now, to your question. To count many births there are per day, you can use value_counts:
births = df['Date'].value_counts()

But you don't even have to do that for plotting a histogram! Use hist:
import matplotlib.dates as mdates
year = mdates.YearLocator()
month = mdates.MonthLocator()
formatter = mdates.ConciseDateFormatter(year)

ax = df['Date'].hist()
ax.set_title('# of births')
ax.xaxis.set_major_locator(year)
ax.xaxis.set_minor_locator(month)
ax.xaxis.set_major_formatter(formatter)

Result (from random data):


text:
Q: Как получить id input vue.js <input id="surname" v-model="name">

<script>
data(){
   name: 'some name'
}
methods:{
  getName(){
      console.log(this.name)
  }
}
</script>

Как получить id элемента input ?

A: Вы можете к вашему input добавить атрибут ref, и в скрипте производить нужные манипуляции, пример ниже:

var app = new Vue({
  el: '#app',
  data: {
    message: ''
  },
  methods:{
    getNameId(){
        console.log(this.$refs.textName.id);
    }
  }
})
<htmL>
  <body>
    <div id="app">
       <input id="surname" ref="textName" v-model="message">
       <button @click="getNameId">test</button>
     </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js">
    </script>
  </body>
</html>


text:
Q: Validation of viewstate MAC failed Error on Azure Web App We are getting Validation of viewstate MAC failed error on an ASP.net application hosted on Azure as a Web App. This problem generally happens when the app is idle for a long time and then an action is performaed using Viewstate. In general on-premise servers, we can fix this by adding machineKey in web.config file. In case of Azure, even after adding machineKey in web.config file, the problem persists
Please advise what am I missing or how can I fix this isuse.

A: You could try to add the following code to the web.config:
<pages enableEventValidation="false" viewStateEncryptionMode="Never">

Here is a similar issue you could refer to .
For more details about resolving view state message authentication code (MAC) errors, please refer to this article.


text:
Q: mac os x 10.6: syslog() EXC_BAD_ACCESS Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x18d1c070
0x96350250 in strlen ()
(gdb) bt
#0  0x96350250 in strlen ()
#1  0x963574d1 in strdup ()
#2  0x9636e420 in asl_set_query ()
#3  0x9636e2d9 in asl_set ()
#4  0x9636d5d2 in vsyslog ()
#5  0x9636d3e1 in syslog ()
#6  0x23405e78 in gp_log (level=4, fmt=0x23429b68 "%-s:%4d: size: %d\n") at ../../rpc/mac/gp_lib.c:49
#7  0x23404c61 in rpc_encap (out=0xbfffb23c, args=0xbfffd2d0) at ../../rpc/rpc.c:178
#8  0x23405269 in rpc_encap_args (pkt_out=0xbfffb20c, pd=0x2342e460, args=0xbfffd2d0) at ../../rpc/rpc.c:120
#9  0x23405549 in rpc_call_common (c=0x23053048, pd=0x2342e460, args=0xbfffd2d0, timeout=0, pkt_in=0xbfffd30c, size_in=0xbfffd308) at ../../rpc/rpc.c:227
#10 0x234057f9 in rpc_call_actor (pd=0x2342e460, args=0xbfffd2d0, timeout=0, pkt_in=0xbfffd30c, size_in=0xbfffd308) at ../../rpc/rpc.c:204
#11 0x23402839 in MobileIPAPIStopRoaming_w () at ../../MIPSDKv4/MobileIPSDK/MobileIP4_w.c:229
#12 0x23401420 in MobileIPAPIStopRoaming (mipHandle=1) at ../../MIPSDKv3/MobileIPSDKv3.c:300
#13 0x21c0e1a6 in GP_ICM_CONNMGR::CMobileIpSdk::MobileIPAPIStopRoaming ()
#14 0x21c0e6cf in GP_ICM_CONNMGR::CMobileIpSdk::Uninit ()
#15 0x1e749c19 in GP_ICM_RULEMGR::CRulesManager::Uninit ()
#16 0x0004df18 in CConnectionManager::UninitConnectionManager ()
#17 0x0013e6b4 in ICMApplication::UninitICMApplication ()
#18 0x001495b2 in main ()
(gdb) info registers
eax            0xffffffff   -1
ecx            0x18d1c07c   416399484
edx            0x18d1c070   416399472
ebx            0x9636e2f0   -1774787856
esp            0xbfffaa4c   0xbfffaa4c
ebp            0xbfffaa78   0xbfffaa78
esi            0x964c6cc0   -1773376320
edi            0x18d1c07c   416399484
eip            0x96350250   0x96350250 <strlen+16>
eflags         0x10286  66182
cs             0x17 23
ss             0x1f 31
ds             0x1f 31
es             0x1f 31
fs             0x0  0
gs             0x37 55
(gdb) frame 1
#1  0x963574d1 in strdup ()
(gdb) frame 2
#2  0x9636e420 in asl_set_query ()
(gdb) frame 3
#3  0x9636e2d9 in asl_set ()
(gdb) frame 4
#4  0x9636d5d2 in vsyslog ()
(gdb) frame 5
#5  0x9636d3e1 in syslog ()
(gdb) frame 6
#6  0x23405e78 in gp_log (level=4, fmt=0x23429b68 "%-s:%4d: size: %d\n") at ../../rpc/mac/gp_lib.c:49
49      syslog(5, "%s", buf);
(gdb) p buf
$5 = "rpc_encap: 178: size: 48\n", '\0' <repeats 998 times>
(gdb) p level
$6 = 4
(gdb) p fmt
$7 = 0x23429b68 "%-s:%4d: size: %d\n"

The gp_log function is this:
#define LOG_DEBUG(format, ...) gp_log(DL_DEBUG, "%-s:%4d: " format, __FUNCTION__, __LINE__, ##__VA_ARGS__)

#define LOG_MAX_LENGTH      1024

void gp_log(int level, const char *fmt, ...)
{
    va_list ap;
    char buf[LOG_MAX_LENGTH] = {0};

    if (level > log_level)
        return;

    va_start(ap, fmt);
    vsnprintf(buf, LOG_MAX_LENGTH, fmt, ap);
    va_end(ap);

    syslog(level, "%s", buf);
    //printf("%s", buf);
}

This statement in rpc_encap print out the contents of an integer, which lead to this crash.
LOG_DEBUG("size: %d\n", size);

The crash is 100% reproduceable. I examine the parameters to syslog() every time before
crash:
buf is always "rpc_encap: 178: size: 48\n".
level is always 4.
If I use printf instead of syslog, the crash disappeared.

A: In order to build a universal library for Mac 10.5/6/7(Intel arch), I add these flags when compiling on 10.6 or 10.7,
CFLAGS = -force_cpusubtype_ALL -mmacosx-version-min=10.5 -arch i386

and crash happened.
Now I remove these flags and build on 10.5, no more crash(also the library works on 10.5/6/7).


text:
Q: argument of type "int" is incompatible with parameter type "int **" I'm writing a 2d array program and i'm having issues getting it to print out, I'm not sure if i'm doing my 2d array passing correct now as its crashing instead of running at all.  Any advice would be helpful
void initialize(int* one, int** two);
void replace(int* arr,int rows, int cols,int value);
void fill(int* arr, int rows, int cols);
void print(int** arr, int rows, int cols);

ofstream outfile;
ifstream infile;
int arrayOne[100][100];
int arrayTwo[100][100];

int main(){

    int rows,cols=0;

    cout << "Please input how many rows you would like in the array:  ";
    cin >> rows;
    cout << "Please input how many columns you would like in the array:  ";
    cin >> cols;

    fill(arrayOne[100][100],rows,cols);
    //print(arrayOne[100][100],rows,cols);

    system("pause");
    return 0;
}

void initialize(int* one, int* two){
    for(int i=0;i<100;i++){
        for(int j=0;j<100;j++){
            arrayOne[i][j]=0;
            arrayTwo[i][j]=0;
        }
    }
}

void replace(int* arr,int rows,int cols,int value){
    arr[rows][cols]=value;
}

void fill(int* arr, int rows, int cols){
    int i=0;
    for(int r=0; r < rows; r++){
        for(int c=0; c < cols; c++){
            replace(arr,r,c,i++);
        }
    }
}

void print(int** arr, int r, int c){
    for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}

A: If you read the error message, it plainly states your problem. That being said, it does not plainly state how to fix it. You're going down a rough path with fixed arrays...
/* arrayOne[100][100] This is an 'int' at the 101st row and 101st column.
 * It isn't an address to anywhere in the array, in fact it is just beyond
 * the end of your array.
 *
 * Regardless, even if it were a pointer, it would point to a location in memory
 * that is not yours. We count starting with 0 in C/C++. So if you'd like to
 * reference the 'whole' array  just pass it bare:
 */
fill (arrayOne, rows, cols);

/* Of course this means that you need to fix the definition of 'fill'
 * and 'replace'.
 */
void replace(int arr[100][100],int rows,int cols,int value){
    arr[rows][cols]=value;
}

/* As you can see this isn't going to be friendly */
void fill(int arr[100][100], int rows, int cols){
    int i=0;
    for(int r=0; r < rows; r++){
        for(int c=0; c < cols; c++){
            replace(arr,r,c,i++);
        }
    }
}

You have other issues, but those can be asked in other questions when you run into them.

A: Change all int* arr and int** arr to int arr[100][] or to arr[][100]. I don't remember which one. but, it's one of them for sure.


text:
Q: CSV file, not keeping leading zeros, what do do I have no idea what to do. Please see below. I need to import this file into another system with the leading zeros. These are sample zip codes as well. I have no idea what is going on. It seems to be an excel issue with CSV files. How can I preseve the leading zeros on a CSV file? Thanks for your help. I haven't had this issue before.
XLSX File
POSTAL_CODE_FORMATTED_TEXT and POSTAL_CODE_FORMATTED_Number
07717

Please see CSV file
CSV File
POSTAL_CODE_FORMATTED_TEXT and POSTAL_CODE_FORMATTED_Number
7717

A: If you would like the edit the column manually you can follow the below steps

*

*Highlight the column

*Right click and select format cells

*On the "Number" tab go to "Custom"

4: Under where it says "Type:" you can enter the amount of digits you want to appear in the column (ex: 00000)


text:
Q: are c++ members not a variable but just a name of a data type? Does the member (declared as a variable) of a struct refer just to the data type of a variable?
for ex:
struct person{

 int age;
 float weight;
 string city;

}mike;
mike.age=43;
mike.weight=130.3;
mike.city="London";

is age refered to the Integer part of the variable mike? and it's just a label to refere to the data type  (because is declared as a variable in the struct)?

A: To answer your question:  No.
Consider a structure with multiple members of the same type:
struct Record
{
  int id;
  int age;
  float money;
  string name;
  string address;
};

The structure doesn't have a single integer, it has more than one integer and more than one string.
The member names help distinguish the fields in the structure.


text:
Q: Counting Problems with n-Bit Strings I'm a little confused with problems regarding n-bit strings- for instance if we are considering the number of n-bit strings of size n with a 1001 pattern, why is it alright to consider only adding things onto one side when generating recurrence relations? Is this an obvious fact, or is it something that generally confuses people? I think I understand that if we consider adding to one side, adding to the other side should be handled when we talk about the number of n-1 bit strings, but it still feels like a leap of faith for me.
For instance, the number of n bit strings with 1001 would be something like the number of n-1 bit strings with 1001 patterns, times 2 by adding a 1 or 0 on the end, plus some other things, but that already confuses me. Initially, I feel as if adding on a 1 or a 0 should be consider for both sides, so I feel like I would want to multiply by 4. Is there a better way of understanding this?

A: You're asking about converse. We should check that both directions work out: going from smaller strings to larger strings, and from larger string to smaller strings.  It sometimes goes without mention from these proofs.
The simplest non-trivial case is $n$-bit strings without $11$ (so let's use this as an example).  Other cases are similar in flavor, but the method of counting might change.

*

*One direction: Given an $n$-bit binary string without $11$:

*

*If it ends with $1$, then it ends in $01$, so we can delete the last two bits to obtain a unique $(n-2)$-bit binary string without $11$.

*If it ends with $0$, then we can delete the last bit to obtain a unique $(n-1)$-bit binary string without $11$.

*The other direction:

*

*Given a $(n-2)$-bit binary string without $11$, we can append $01$ to the end to get a unique $n$-bit binary string without $11$.

*Given a $(n-1)$-bit binary string without $11$, we can append $0$ to the end to get a unique $n$-bit binary string without $11$.
This gives a bijection between the $n$-bit strings without $11$ and the $(n-1)$-bit strings without $11$ $\bigcup$ the $(n-2)$-bit strings without $11$.  This is illustrated below:

We could proceed similarly and add bits at either end.  It doesn't make the proof any easier though.  If we did that in the above case:

*

*Every $n$-bit string without $11$ would be paired up with exactly $2$ smaller strings without $11$ (either $(n-1)$-bit or $(n-2)$-bit).

*Every $(n-1)$-bit and $(n-2)$-bit string without $11$ would be paired up with exactly $2$ $n$-bit strings.
So the number of edges in the figure would double, but the result would still hold:  The number of edges going out of the left is $2$ times the number of $(n-1)$-bit strings without $11$ plus the number of $(n-2)$-bit strings without $11$.  This is equal to the number of edges going into the right, which is $2$ times the nmber of $n$-bit strings without $11$.  So the $2$'s cancel out and we get the same recurrence.


text:
Q: Parse error in PHP (t_string) I am getting error in following code.  Parse error: syntax error, unexpected 'size' (T_STRING) in line 7. Please help

<?php
function fontWrap( $txt, $size ) {
print "
$txt";
}
fontWrap("A heading
",5);
fontWrap("some body text
",3);
fontWrap("some more body text
",3);
fontWrap("yet more body text
",3);
?>

A: You're using funky quotes. Change " and " to ".
And stop using MS Word as a text editor. :)

A: NM: looks like the quotes was the problem. Not the lack of parentheses.
print("$txt");

Although, you might want to use CSS and span tags and make a function to insert the tag for this by defining a CSS style sheet that defines standard font-family and sizes so your presentation is separate from your content, and more consistent (note: most typography uses different sizes sparingly — 1 each for head, subhead, body and caption usually) as well as making changes easier. (If you change the size smaller or larger then each function call in the script will have to be searched for and replaced with new values, assuming it is present in multiple places).
In the css:
body{
    font-family: Helvetica, Arial, Sans-Serif;
.heading {
    font-size: 2em;
}
.normal {
    font-size: 1em;
}
.note {
    font-style: italic;
    font-size: .5em;
}
.subhead {
    font-size: 1.5em;
}

Later in the php class or global functions:
public function spanClass($copy,$class){
    print("$copy");
}

In the php webpage itself:
spanClass("Cool Things","heading");
…
spanClass("& Other Stuff","subhead");

http://us1.php.net/manual/en/function.print.php


text:
Q: Docker or Docker for AWS and Deployment on AWS EC2 2 Questions here.
Im trying to figure out what is the main difference between the normal Docker and Docker for AWS.
For my project i will run a GUI coded in Angular 2, packed in a Docker Container on an AWS EC2.
1) Should i use Docker for AWS for my purpose?
2) Is it possible that Docker can [1]get my Code from an GITHUB repository and [2]build it when i run docker?
3) What is the Best way to deploy an Docker Container on AWS?
is there a guide to follow or some best practise examples?
Thank you in advance!

A:
1) Should i use Docker for AWS for my purpose?

Docker for AWS provides self-healing infrastructure through CloudFormation. If you need auto-scaling for your application, then this is a good route to take. However, the cost will add up.

2) Is it possible that Docker can [1]get my Code from an GITHUB repository and [2]build it when i run docker?

Using GitHub web-hooks / integrations, you can have your image built for you, through Jenkins / Travis / ANOther CI tool. This can publish an image to the Docker Hub, or a self-hosted / third party registry.

3) What is the Best way to deploy an Docker Container on AWS? is there a guide to follow or some best practise examples?

Every use-case is different. Is this for testing? demos? production? Too many factors to tackle this I'm afraid.
Edit:

3) It is for Demos porpuse at the moment

I'd just spin up a single EC2 instance and install the docker-engine and use that

A: As @Rawkode explain everything well. I will just add something to your last point.
For running docker based application using ec2 instance you can use

Deploy Docker Containers on Amazon EC2 Container Service (Amazon ECS)

Amazon EC2 Container Service (Amazon ECS) is the Amazon Web Service you use to run Docker applications on a scalable cluster.
You can run your angular app using docker. as you mention in a comment that you can use ng build --prod. Which build and create dist folder for you.Here how I deploy angular docker based application in AWS.
first, create an express server which will serve your static file.
   var express =     require('express');
   var path = require('path');
   var router = express.Router();
   var app = express();
   // serve angular front end files from root path
   app.use('/', express.static('dist', {
       redirect: false
   }));
   // rewrite virtual urls to angular app to enable refreshing of internal
   pages
   app.get('*', function(req, res, next) {
       res.sendFile(path.resolve('dist/index.html'));
   });

   app.listen(3000, function(req, res) {
       console.log("start");
   })

so this will serve your angular static file and S3 you will face the error on refresh which can be resolved using re-write rule.
create your docker file for express and express will deal with static file
    FROM alpine
RUN apk update && apk upgrade
RUN apk add nodejs
RUN mkdir -p /app
ADD app/package.json /app
WORKDIR /app/
ENV HOME /app
ENV NODE_ENV development
RUN npm install
ADD app /app
EXPOSE 3000
CMD npm start

inside app folder where express server file, place dist folder in the same directory.
now for deploy your docker based application visit this link
https://aws.amazon.com/getting-started/tutorials/deploy-docker-containers/
Best Practices for Hosting Web Applications on AWS
This above I just tried to explain how to run the angular application on AWS ECS and you can make it more good by running multiple copies of same task and configure load balancer.
As for best practices is concern for web application
For static Application

for more detail best-practices-for-hosting-web-applications-on-aws
Docker and AWS have teamed up to make it easier than ever to deploy an enterprise Containers as a Service (CaaS) Docker environment on Amazon's EC2 infrastructure. Running Docker Datacenter on AWS gives developers and IT operations a highly reliable, low-cost way to deploy production-ready workloads in a single click.
https://www.docker.com/aws
secrets-for-amazon-ec2-container-service
aws-for-startups-architectural-best-practices-automating-your-infrastructure


text:
Q: R: date/time YYYY-MM-DDThh:mm:ss.SSSZ formate How can I change the type of variable data$timestamp from char to date format YYYY-MM-DDThh:mm:ss.SSSZ date/time in R ? I'm willing to keep all information within this format.
2014-04-06T18:42:05.823Z

A: You can use as.POSIXct to have an object of class "POSIXct".
x <- "2014-04-06T18:42:05.823Z"

op <- options("digits.secs" = 3)

d <- as.POSIXct(x, tz = "UTC", "%Y-%m-%dT%H:%M:%OS")
d
#[1] "2014-04-06 18:42:05.822 UTC"

class(d)
#[1] "POSIXct" "POSIXt"

format(d, "%Y-%m-%dT%H:%M:%OS3")
#[1] "2014-04-06T18:42:05.822"

See help("strptime") for data time formats.
Note.
as.POSIXct and strptime may give different results, depending on the time zone.
as.POSIXct(x, tz = "UTC", "%Y-%m-%dT%H:%M:%OS")
#[1] "2014-04-06 18:42:05.822 UTC"
strptime(x, tz = "UTC", format = "%Y-%m-%dT%H:%M:%OS")
#[1] "2014-04-06 18:42:05.823 UTC"

The last digit is off by 1.


text:
Q: Android SSL TLS connection to XMPP server I am trying to connect to an XMPP server requiring "Encryption (SSL or TLS)". I cannot use Smack or other third-party libraries (school project)
Here is my Java code to initialize an SSL socket :
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
socket = sslContext.getSocketFactory().createSocket(HOST, PORT);
socket.setKeepAlive(true);

If I try to open the stream on the socket:
socket.getOutputStream()

I get this error :
javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x76cb46a0: Failure in SSL library, usually a protocol error

error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:766 0x72fb3d74:0x00000000)

at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:448)

Does anyone know where is the issue from ?

A: From having a short look at the XMPP core specification it does not look like you can simple use a socket and upgrade it immediately to TLS. Instead you have to first use some kind of STARTTLS command and only after that you can upgrade to TLS. This is similar to explicit TLS in SMTP, IMAP etc.
For more details please see the specification. Some shorter information you will find here.


text:
Q: How NetBeans dependency copy work and does it work for two times nested apps? If my application(main app) use external jars(libs) that use external jars(libs), I need to copy dependency, so I would like to know how it works behind the scene?
Second, is it possible to have application that uses ServiceLoader to import extensions, whice inside themself call ServiceLoader? Right now I make application that imports extensions with ServiceLoader, and that works fine with module paths, but if my extensions also have ServiceLoader, where I'm setting their module path if that is even possible?


text:
Q: Error while installing UberCart or Drupal Commerce on Drupal 7.x I have Drupal 7 and when I am installing modules Ubercart, Rules and Entity API or Drupal Commerce, Rules, Entity API I am getting the following error
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.owner' in 'field        list': SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.owner AS owner, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => reaction rule [:db_condition_placeholder_1] => 1 ) in EntityAPIController->query() (line 187 of C:\xampp\htdocs\sites\all\modules\entity\includes\entity.controller.inc).

Could you please help me with this kind of error?
Thank you in advance

A: Try to reinstal it and use latest version of modules, something went wrong. I'd recommend using Drupal Commerce insead of D7 + Ubercart since Ubercart is obsolete.


text:
Q: Запуск python файлов на другом устройсве Мне нужно (хотя бы в теории) узнать, как запустить (или чтобы она сама запускалась) какую-либо python программу на устройстве, в котором отсутствует python.
Имею ввиду то, что после отправки файла от меня к другому человеку, он 100% запустился,  исключая то, что человеку (которому файл был отправлен) пришлось бы самостоятельно что-то докачивать (к примеру, тот же питон).

A: Можно скомпилировать python на Windows при помощи pyinstaller или же py2exe.
Ещё были pyWin32, cx_freeze для тех же целей.
На *nix pyhton практически всегда есть в дефлотной поставке.

A: Единственный способ - это упаковка скриптов вместе с компактной версией интерпретатора в самораспаковывающийся архив с помощью cx_freeze, pyinstaller и тому подобного.


text:
Q: Wants to Populate HTML table with objects containing an array using Vue 2.*
data:  [ {"column_name":"respond_by","old_value":"0000-00-00
  00:00:00","new_value":"2017-12-06 00:00:00"},
{"column_name":"client_id","old_value":"163270275","new_value":"535987752"},
{"column_name":"violation_date","old_value":"0000-00-00
  00:00:00","new_value":"2017-10-23 00:00:00"} ]

this is my HTML:

        {{ value.column_name }}
        {{ value.old_value }}
        {{ value.new_value}}

I would like the Column Name to go in the first column and the 2nd Column is for the old Value and the 3rd is for the New Value. Hope someone with more Vue knowledge is able to help me out here.


text:
Q: Which best algorithm for my list management? I am struggling with one algorithm. I want to do some actions ( update, delete, add elements) on the current list from data sumbitted one the second list.
My first list currentList and the submitted List submittedList
The problem i have to resolve is that:

*

*If a element of the currentList is in the submittedList, this element must be updated in the currentList

*If a element of the currentList is not in the submittedList, this element must be delete from the currentList

*All the  a element of the submittedList that are not in the currentList must be add to the currentList

If you could help please, thanks

A: Think this in a different way. You need the currentList to have only objects in submittedList, but just need to modify the object if its present in both the lists. So your algorithm has only two steps.
My suggestion would be to go with a temporary list. I have added a solution below assuming that the objects in your lists are Strings. (You can replace String with your custom object)
List<String> tempList = new ArrayList<String>();
for(String test : submittedList) {
    if(currentList.contains(test)) {
        String test1 = test+"xyz"; // do modification to test String
        tempList.add(test1);
    } else {
        tempList.add(test);
    }
}
currentList.clear(); // Now add to the actual list after clearing
currentList.addAll(tempList);

A: If you can, sort both lists. Then scan them in increasing order: read the first elements c and s from currentList and submittedList. If c==s, update c and get the next c and s; if c<s (meaning that c is not in submittedList), discard c from currentList and get the next c; if c>s (meaning that s is not in currentList), insert s in currentList and get the next s. And so on.
When one of the list is exhausted, continue with the rules c<* and *>s. Stop when both lists are exhausted.


text:
Q: check that $x,y,z$ span a 3-dimensional Lie subalgebra $L$ of $\mathbb{gl}(V)$ Suppose $V$ is a 3-D vector space over a field $k$ with basis $B=\{v_1,v_2, v_3\}$ and consider the linear operators $x,y,z\in\mathbb{gl}(V)$ whose matrices with respect to $B$ are some 3 by 3 $X, Y$ and $Z$.
How would one go about verifying $[x,y],[x,z],[y,z]$ are linear combinations of $x,y,z$ and finding these combinations (i.e check that $x,y,z$ span a 3-dimensional Lie subalgebra $L$ of $\mathbb{gl}(V)$)?


text:
Q: jQuery: How to get the difference between time with 12hr format and time with 24hr format I'm new in jQuery and I really don't know have any idea how to get this. I want to get the 12hr format result of the difference between time with 12hr format and time with 24hr format. Example: given the time "1:30:25 AM" and subtract it to "00:32:20", then the result should be "12:58:05 AM". Please help me to get this.

A: Result in 24-hr format
var dt = '1/1/2000 ';
var date = new Date(new Date(dt + '1:30:25 AM') - new Date(dt + '00:32:20'));
alert("24-hr format: " + date.toISOString().substr(11, 8));

Result: 00:58:05
Result in 12-hr format
function timeFormat12Hr(date) {
    var hours = date.getUTCHours();
    var minutes = date.getUTCMinutes();
    var seconds = date.getUTCSeconds();
    var ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    seconds = seconds < 10 ? '0' + seconds : seconds;
    var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
    return strTime;
}

var dt = '1/1/2000 ';
var date = new Date(new Date(dt + '1:30:25 AM') - new Date(dt + '00:32:20'));
alert("12-hr format: " + timeFormat12Hr(date));

Result: 12:58:05 AM
NOTE: I'm using string '1/1/2000 ' to construct a Date object, but it could be any date because we're only interested in time portion of it.
See this JSFiddle for demonstration.

A: Some simple javascript should do the job. Once you have a date object you can output it in whatever format you want.
var year = 2015; var month = 5, var day = 18, var hours = 1; minutes = 30; seconds = 25;
var date = new Date(year, month, day, hours, minutes, seconds, milliseconds);
var new_format = (date->getHours()+1)+'-'+date->getMinutes();

date returns 0-23 so you have to add +1 (this is why i tend to favor moment.js, as mentioned below)
http://www.w3schools.com/jsref/jsref_obj_date.asp (for other methods of creating date object)
Otherwise maybe give moment.js a try, it's awesome for date/time calculations.
http://momentjs.com/


text:
Q: how to do custom filtering and custom pagination I am not using Entity framework, i have created custom Data Access Layer.
i want to do custom filtering and custom pagination.
does grid.mvc supports custom pagination and custom filtering?
i have checked http://gridmvc.codeplex.com/documentation documentation, but can not find how to do it.
i have tried
EnablePaging = true;
Pager.PageSize = 10;

but it will do pagination on already paged data.
if anybody had done it, please suggest how it can be done.
Thanks in advance.

A: I haven't worked with grid.mvc, but you can do paging and filtering on virtually any sequence in .NET using LINQ.
var items = new List<string>();

// Add 10 items for testing
for (int i = 0; i < 10; i++)
{
    items.Add("item" + i.ToString());
}

var pagedAndFilteredItems = items
    .Where(x => x != "item0") // Filter the first item from the sequence
    .Skip(3) // Number of items to skip over
    .Take(3) // Number of items to put into the current view.
    .ToList(); // Executes the query

// pagedAndFilteredItems now contains
// "item4"
// "item5"
// "item6"
// Which corresponds to the second page if your page size is 3

You could then only provide 1 page at a time to grid.mvc. You might have to build your own next and back links, but if you are pulling data from an external source, this is far more scalable than providing the entire dataset to the grid.
Of course, another option is to do the filtering in LINQ as shown with the Where clause and then have grid.mvc do the pagination.


text:
Q: Django FieldError How do I request the current user? I want to do something like
if user.id == pk
    # something sinister

where pk is the string used in the urls.py as a regular expression search term. I want the user to only be able to go to the folder that is assigned to him via his own primary key. Currently my half-assed function looks like this:
def permit(request, pk):
    u = User.objects.get(user=request.user)
    if user.id == pk:
        pass
    else:
        return render_to_response('forbidden.html')

This is the view function that the urls.py redirects to. This, however, returns an error:
FieldError: Cannot resolve keyword 'user' into field. Choices are: date_joined, document, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, user_permissions, username

A: if int(request.user.id) == int(pk):
    pass

try to print pk, request.user.id and type(...) of both this values


text:
Q: How to include a model inside my index view I have two model Event, and Photo with the following relationships:
Event
has_many :photos
accepts_nested_attributes_for :photos, :allow_destroy => true

Photo
belongs_to :event

When I create it in my Event#new controller I have the following
@event = Event.new
@event.photos.build

This is my Event#form view inside the form
<%= form_for(@event) do |f| %>
...
  <%= fields_for :photos do |photo| %>
    <%= photo.file_field :picture %>
  <% end %>
<% end %>

And now I want to include the first photo because you may have more than one set related to this to show in Event#index.
I try this but it seem to fails:
<% @events.each do |event| %>
  <% event.photos.first do |pict| %>
    <%= pict.image... %>
  <% end %>
<% end %>

A: You might need to add :multipart => true to your form_for block if you have a file field in the form. That could explain why it's not uploading.

A: I'm going to guess that it doesn't do anything because #first doesn't take a block. Try
<%= event.photos.first.image... %>

event.photos.first returns a single object, and passing a block (e.g. the do |photo| ... end part) to an object doesn't really do anything.
BTW, it would be helpful if you include a little more detail on what "it fails" means. Do you get a stack trace? Does nothing show on the page? Have you verified in the console that your Event object has one or more Photos?

A: Change <%= fields_for :photos do |photo| %> into <%= f.fields_for :photos do |photo| %>.
<% event.photos.first do |pict| %> is wrong - just get first picture and try accessing it (if it exists):
<% pict = event.photos.first %>
<% if pict %>
code here
<% end %>


text:
Q: How can I store a part of a very large HTML stream? I have to get the HTML code of a web and after that to find this class:
0,896903

I have tried with Regular-Expressions.
And also with Streams, I mean, storing the whole HTML code in a string. However, the code is very large for a string. So that makes it impossible, because the amount 0,896903 I am searching does not exist in the string.
Is there any way to only read a little block of the Stream?
A part of the method:
public static string getValue()
        {
            string data = "not found";
            string urlAddress = "http://www.xe.com/es/currencyconverter/convert/?Amount=1&From=USD&To=EUR";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = null;

                if (response.CharacterSet == null)
                {
                    readStream = new StreamReader(receiveStream);
                }
                else
                {
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                }

                data = readStream.ReadToEnd(); // the string in which I should search for the amount

                response.Close();
                readStream.Close();
            }

If you find an easier way to fix my problem let me know it.

A: I would use HtmlAgilityPack and Xpath
var web = new HtmlAgilityPack.HtmlWeb();
var doc = web.Load("http://www.xe.com/es/currencyconverter/convert/?Amount=1&From=USD&To=EUR");
var value = doc.DocumentNode.SelectSingleNode("//span[@class='uccResultAmount']")
               .InnerText;

A Linq version is also possible
var value = doc.DocumentNode.Descendants("span")
            .Where(s => s.Attributes["class"] != null && s.Attributes["class"].Value == "uccResultAmount")
            .First()
            .InnerText;

Don't use this. Just to show

But the problem is that this html code does not fit in a single string

is not correct
string html = new WebClient().DownloadString("http://www.xe.com/es/currencyconverter/convert/?Amount=1&From=USD&To=EUR");
var val = Regex.Match(html, @"]+?class='uccResultAmount'>(.+?)")
               .Groups[1]
               .Value;


text:
Q: Singular value decomposition - determinant I know that when expressing a matrix $A$ in SVD, the determinant of $A$ can be calculated by finding the product of the singular values $\sigma_1 *... *\sigma_n $. My question is, does this hold true only for non-zero values of $\sigma_i$? So for instance, I am given the singular matrix given below:
$\Sigma$ = $$
    \begin{bmatrix}
    4 & 0 & 0 & 0 \\
    0 & 2 & 0 & 0 \\
    0 & 0 & 1 & 0 \\
    0 & 0 & 0 & 0 \\
    \end{bmatrix}
$$
Would the determinant in this case be 0? Or would we just multiply the non-zero singular values to get a determinant of $8$?

A: Consider a matrix $A$ which has an SVD as $A = U \Sigma V^{T}$
$$ \det(A) = \det(U \Sigma V^{T})  \\ = \det(U)\det(\Sigma) \det(V^{T}) \\ = \det(U)\det(\Sigma) \det(V) $$
now the determinant of an orthogonal matrix like $U,V$ is $\pm 1$
$$  \det(U) , \det(V) = \pm 1 \implies \\ |\det(A)| = \det(\Sigma) $$
Additionally the determinant of a diagonal matrix is the product of the diagonal
$$  \det(D) = \prod_{i} \textrm{diag}(D)_{i} $$
So the determinant of $A$ is
$$   |\det(A)| = \prod_{i} \textrm{diag}(\Sigma)_{i} $$
now if any singular value $\sigma_{i} = 0$ then the entire product will be $0$


text:
Q: PyQt5 - Position a widget at top right corner of a QTextEdit I'm developping a text editor with pyqt5 and I want to implement a Find Box which  sticks to the top right corner of my textarea just like this:
image

textarea = QTextEdit()
layout = QHBoxLayout() # tried hbox, vbox and grid
find_box = QLineEdit()
empty = QTabWidget()
layout.addWidget(empty)
layout.addWidget(empty)
layout.addWidget(find_box)
textarea.setLayout(layout)

So with this code, I managed to have my Find Box stick to the left of my texarea, even when window gets resized. But somehow the y position of my textarea's layout starts from the middle:
image

An awful solution is to set the textarea as my Find Box parent, use move(x, y) to set the Find Box's position but I'll have to catch whenever my window or my textarea get resized and use move() again to set a new position.
So why my QTextEdit's layout starts from the middle? And is there anyway to avoid this?

A: I got it working by using a gridlayout and setting stretch factors to rows and columns.
from PyQt5.QtWidgets import *
import sys

class Wind(QWidget):
    def __init__(self):
        super().__init__()
        self.setupUI()

    def setupUI(self):
        self.setGeometry(300,300, 300,500)
        self.show()
        text_area= QTextEdit()
        find_box = QLineEdit()

        # this layout is not of interest
        layout = QVBoxLayout(self)
        layout.addWidget(text_area)

        # set a grid layout put stuff on the text area
        self.setLayout(layout)

        text_layout= QGridLayout()

        # put find box in the top right cell (in a 2 by 2 grid)
        text_layout.addWidget(find_box, 0, 1)

        # set stretch factors to 2nd row and 1st column so they push the find box to the top right
        text_layout.setColumnStretch(0, 1)
        text_layout.setRowStretch(1, 1)

        text_area.setLayout(text_layout)

def main():
    app= QApplication(sys.argv)
    w = Wind()
    exit(app.exec_())

if __name__ == '__main__':
    main()


text:
Q: Catching an error "java.lang.RuntimeException: Stub" while getting instance for FireBase in Kotlin I'm trying to create simple Telegram Bot in Kotlin with FireBase database resources:
import com.google.firebase.database.*
import dev.inmo.tgbotapi.bot.ktor.telegramBot
import dev.inmo.tgbotapi.extensions.api.answers.answerCallbackQuery
import dev.inmo.tgbotapi.extensions.api.bot.getMe
import dev.inmo.tgbotapi.extensions.api.send.sendTextMessage
import dev.inmo.tgbotapi.extensions.behaviour_builder.buildBehaviourWithLongPolling
import dev.inmo.tgbotapi.extensions.behaviour_builder.expectations.*
import dev.inmo.tgbotapi.extensions.behaviour_builder.triggers_handling.onCommand
import dev.inmo.tgbotapi.requests.send.SendTextMessage
import dev.inmo.tgbotapi.types.buttons.InlineKeyboardButtons.CallbackDataInlineKeyboardButton
import dev.inmo.tgbotapi.types.queries.callback.MessageDataCallbackQuery
import kotlinx.coroutines.flow.first

    private lateinit var result: MessageDataCallbackQuery
    private lateinit var mDataBase: DatabaseReference
    private lateinit var data: String

    suspend fun main() {

        val bot = telegramBot("ХХХХХХХХХХХХХХХХХХХХХMlwKn5YH48c")

        mDataBase = FirebaseDatabase.getInstance("https://ХХХХХХХХХХХХХХХХХbase.app/").reference

        mDataBase.child("welcome").addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(data: DataSnapshot) {
                data = data.value.toString()
            }
            override fun onCancelled(error: DatabaseError) {
            }
        })

        bot.buildBehaviourWithLongPolling {
            println(getMe())

            val inlineKeyboard = dev.inmo.tgbotapi.types.buttons.InlineKeyboardMarkup(
                keyboard = listOf(
                    listOf(
                        CallbackDataInlineKeyboardButton(
                            "\uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBC about",
                            "about"
                        )
                    ),
                    listOf(
                        CallbackDataInlineKeyboardButton(
                            "\uD83C\uDF08 methods",
                            "methods"
                        )
                    ),
                    listOf(
                        CallbackDataInlineKeyboardButton(
                            "\uD83D\uDCCA costs",
                            "costs"
                        )
                    ),
                    listOf(
                        CallbackDataInlineKeyboardButton(
                            "\uD83D\uDCCA record",
                            "record"
                        )
                    )
                )
            )

            onCommand("start") {
                result = waitMessageDataCallbackQuery(
                    SendTextMessage(
                        it.chat.id,
                        "Пожалуйста, что бы Вы хотели узнать?",
                        replyMarkup = inlineKeyboard
                    )
                ).first()

                answerCallbackQuery(result.id)

                if (result.data == "about") {
                    sendTextMessage(
                        it.chat,
                        "обо мне"
                    )
                }
            }
        }.join()
    }

But it throws an error while compiling:
Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.google.firebase.FirebaseApp.<clinit>(FirebaseApp.java:100)
    at com.google.firebase.database.FirebaseDatabase.getInstance(FirebaseDatabase.java:71)
    at space.project.mesbot.MainActivityKt.data(MainActivity.kt:59)
    at space.project.mesbot.MainActivityKt.main(MainActivity.kt:71)
    at space.project.mesbot.MainActivityKt$main$3.invoke(MainActivity.kt)
    at space.project.mesbot.MainActivityKt$main$3.invoke(MainActivity.kt)
    at kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt$createCoroutineUnintercepted$$inlined$createCoroutineFromSuspendFunction$IntrinsicsKt__IntrinsicsJvmKt$1.invokeSuspend(IntrinsicsJvm.kt:205)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlin.coroutines.ContinuationKt.startCoroutine(Continuation.kt:115)
    at kotlin.coroutines.jvm.internal.RunSuspendKt.runSuspend(RunSuspend.kt:19)
    at space.project.mesbot.MainActivityKt.main(MainActivity.kt)
Caused by: java.lang.RuntimeException: Stub!
    at android.os.Looper.getMainLooper(Looper.java:30)
    at com.google.firebase.FirebaseApp$UiExecutor.<clinit>(FirebaseApp.java:718)
    ... 11 more

I've checked everything: libraries, dependencies, manifest etc - everything in the same way as I did lot's of times previously in other apps. May be something connected to suspend fun???


text:
Q: Symmetric Grothendieck inequality Grothendieck's inequality states that for all $n \times n$ matrices $(a_{ij})$ such that
$$\max_{x \in \{\pm 1\}^n,\, y \in \{\pm 1\}^n} \left|\sum_{ij} a_{ij}\, x_i\, y_j\right| \leq 1,$$
there exists a universal constant $K$, such that for $u_i, v_j$ in any Hilbert space,
$$
\max_{x \in \{\pm 1\}^n,\, y \in \{\pm 1\}^n} \left|\sum_{ij} a_{ij} \langle u_i , v_j \rangle \right| \leq K.
$$
I would like to prove the symmetric statement.  For all symmetric matrices $(a_{ij})$ such that
$$
\max_{x \in \{\pm 1\}^n} \left|\sum_{ij} a_{ij} \,x_i\, x_j\right| \leq 1,
$$
there exists a universal constant such that
$$
\max_{x \in \{\pm 1\}^n} \left|\sum_{i,j} a_{ij} \langle u_i , v_j \rangle \right| \leq 2K
$$
for $u_i, v_j$ in any Hilbert space.  This should be a consequence of the original inequality.  I tried to use the polarization identity
$$
\langle Ax, y\rangle = \langle Au, u\rangle - \langle Av, v \rangle
$$
where $u = (x+y)/2$ and $ v = (x-y)/2$.  However, as $x$ and $y$ vary over $\pm 1$ vectors, $u$ and $v$ can be vectors in $\{\pm 1, 0\}$.

A: I think this is an exercise from Vershynin's book. The statement does not seem correct without further assumptions of $A$.
[Update in March 2020: The electronic version of the book, available on Vershynin's homepage, has corrected this problem.]
For example, take
$$
A = \begin{pmatrix} -1000 & 0 \\ 0 & 1000 \end{pmatrix}
$$
Then it holds for any $x\in \{-1,1\}^2$ that
$$
\sum_{i,j} A_{ij} x_i x_j = 0.
$$
But when $x=(1,1)$ and $y=(-1,1)$, we have
$$
\sum_{i,j} A_{ij} x_i y_j = 2000.
$$
A possible remedy is to assume that

*

*the diagonal entries of $A$ are all $0$s, or

*$A$ is PSD.

Before we prove our results, we first prove the following claim.
Claim. Let $I\subseteq \{1,\dots,n\}$ be an arbitrary subset. Then it holds for all $x\in \{-1,1\}^n$ that
$$
-1 \leq \sum_i a_{ii} + \sum_{\substack{i,j\in I\\ i\neq j}} a_{ij}x_i x_j \leq 1.
$$
Proof of Claim. Fill up the coordinates of $x$ outside $I$ using $\{-1,1\}$ and there are $M = 2^{n-|I|}$ possibilities, call those filled vectors $x_1,x_2,\dots,x_M$. Then we have for each $\ell=1,\dots,M$,
$$
-1 \leq \sum_i a_{ii} + \sum_{i\neq j} a_{ij} (x_\ell)_i (x_\ell)_j \leq 1.
$$
Summing over all $M$ such inequalities we have
$$
-M \leq M\sum_i a_{ii} + M \sum_{\substack{i,j\in I\\ i\neq j}} a_{ij} x_i x_j \leq M,
$$
which proves the claim.
Then we can prove the following: if $|\langle Ax,x\rangle|\leq 1$ for any $x\in \{-1,1\}^n$, then $|\langle Ax,x\rangle|\leq 1$ for any $x\in \{-1,0,1\}^n$. The final result will follow from Grothendieck's inequality immediately, using the polarization identity.
Now we prove the claim above in the two cases of remedy.

*

*When $A$ has zero diagonal entries, we have for any subset $I\subseteq \{1,\dots,n\}$ that
$$
-1 \leq \sum_{i,j\in I} a_{ij} x_i x_j \leq 1,
$$
The the earlier claim follows by setting $I$ to be the support of $x$.

*When $A$ is PSD, then $0\leq \langle Az,z\rangle$ already holds and it suffices to show that $\langle Az,z\rangle \leq 1$. Since $A$ is PSD, the diagonal entries are nonnegative, it follows from the claim $\langle Az,z\rangle + \sum_{i\not\in \operatorname{supp}(z)} A_{ii}\leq 1$ that $\langle Az,z\rangle\leq 1$.

A: I would like to point you to this paper, and I feel there should be a satisfactory answer there.
https://arxiv.org/abs/2003.07345


text:
Q: Interaction with linux console in python How I can interaction with linux console in python. Open (or not) window with console, and do any command or just typing something and press enter

A: For example:
import os
os.system('ls')

A: I like to use both subprocess and os.
These python modules dont necessarily 'open a console and run a command' rather they interface with your shell.
import os
import subprocess

eg
fileCount = int(subprocess.check_output('ls dir/ | wc -l', shell=True).decode().strip())

or
pathToOldest = './someDir/' + oldestFileInDir
os.remove(pathToOldest)

If youre looking to do run a particular command I would go to a search engine and type 'python run shell commmands' or 'run {enter shell command} in pythonX}


text:
Q: Symbol OR end of line pattern I need a pattern (java regexp) which matches if there is a comma after key or key is at the end of line. i.e it should match both of followings:
1. xxxkey,yyy
2. xxxkey

Ive tried [\\,$] pattern but it doesn't work.

A: $ inside a character class loses its special meaning. Use the following instead:
key(,|$)

If you don't need to know whether there was a comma, you can use a non-capturing group instead:
key(?:,|$)

A: Try this...
"xxxkey(?:,\\w*)?$"

or -
"xxxkey(?:,.*)?$"

or -
"xxxkey(?:,|$)"

Depending on your needs

A: Here's what you need :
.*key((,.*)|$)

A: The , is a character, but the $ is special, it's not a character.
Try ,? which means one comma or no commas and follow that with $.


text:
Q: Белый экран смерти в yii2 Всем привет! Мне кажется, моё приложение сошло с ума. Периодически на определенных страницах моего приложения выбрасывает белый экран, вместо страницы, исходный код абсолютно пуст, причем белый экран иногда сменяется 502 bad gateway, включил в yii отображение всех ошибок, index.php
error_reporting(-1);
ini_set('display_errors', true);
ini_set('display_startup_errors', true);

Белый экран пропадает и выводятся Notice ошибки, фатальных ошибок нет. Причем что самое странное после перезагрузки сервера все становится нормально, белый экран перестает появляться. Когда я пытаюсь перейти на страницу с белым экраном, кликнув по ссылке, то на странице вообще ничего не происходит, страницы как бы подвисает, появляется курсор навигации по тексту (I), браузер через какое то время говорит, что страницу загрузить не удалось. Я даже не знаю в какую сторону копать и что делать, кроме как перегружать сервер... может кто-нибудь сталкивался с подобным? В какую сторону копать?
nginx/1.6.3
PHP 5.5.30

A: Включите в настройкаъ php логгирование ошибок.
В рантайме можно сделать так:
ini_set("log_errors", 1);
ini_set("error_log", "path/to/php-error.log");

Посмотрите на логи, которые пишет framework, в папку runtime/logs/, изучите логи, исправьте ошибки и "экран смерти" пропадёт.
P.S.: В Yii2 уставновите деббагер - https://github.com/yiisoft/yii2-debug , но не используйте его на продакшене.


text:
Q: Showing ((A→B)→A)→A. and A,B ⊢ ¬(A→¬B) using Deduction Theorm, etc. Using the Deduction Theorem and the principles of Ex Falso, Reductio ad Absurdum, and Indirect Proof, I am to show that:

(a) $$((A→B)→A)→A$$

and

(b)   $$A,B ⊢ ¬(A→¬B)$$

I know how to forumlate the principles mentioned and I also intuitively see that (a) and (b) are valid. My problem, however, is that I actually can't figure out how to use the principle mention to show this ...
I would love it if someone could offers some assistance in showing how we apply the principle in order to show (a) and (b).

A: For (a) [Peirce's law] see this post : it is enough to omit steps 1) and 13).
For (b) :

$A,B \vdash ¬(A → ¬B)$

we have the following proof :
1) $A$ --- premise
2) $B$ --- premise
3) $A → ¬B$ --- assumed [a]
4) $¬B$ --- from 1) and 3) by $\to$-elimination (modus ponens)
5) $\bot$ --- from 2) and 4) by $\lnot$-elimination

6) $\lnot (A → ¬B)$ --- from 3) and 5) by $\lnot$-introduction, discharging [a].

Thus, steps 3) to 6) are nothing more than an Indirect Proof : assume  the negation of the sought conclusion and derive a contradiction.


text:
Q: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: null near line 1,
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:
null near line 1, column 226 [SELECT COUNT(*) FROM
com.pmp.vupadhi.model.EmpLeave  WHERE ((start_date >=:startdate AND
start_date <=:enddate) OR (end_date >=:startdate AND end_date
<=:enddate)) AND em_id =:id AND (leave_status !=103 AND leave_status
!=104]

A: You are missing a closing parenthesis ) at the end.

A: Can you try <> operator for not equal to.
leave_status <> 104

Also give an alias and then do COUNT(alias) instead of a *.

A: You might have a null parameter even when you do not expect that.
Try logging the parameters like described in https://www.baeldung.com/hibernate-logging-levels and check for null values.


text:
Q: Determine user sessions in Mysql how can I determine the session times of these fictitious users?
As an example, for user 1 I assume that between 08:24:08 and 15:08:20 he wasn't there, so I don't add that time interval, I add the other times.
So I look for a method to add up (in seconds or minutes) the intermediate times based on this table. Any ideas.
drop table sessions;
CREATE TABLE IF NOT EXISTS sessions (
    id_user int(11),
    start_date datetime
);

insert into sessions values (1,'2020-02-21 08:24:07');
insert into sessions values (1,'2020-02-21 08:24:08');--> 1 seg (08:24:08 - 08:24:07)
insert into sessions values (1,'2020-02-21 15:08:20');
insert into sessions values (1,'2020-02-21 15:08:21');--> 1 seg (15:08:21 - 15:08:20)
insert into sessions values (1,'2020-02-21 15:08:22');--> 1 seg
insert into sessions values (2,'2020-02-20 15:08:22');
insert into sessions values (2,'2020-02-20 15:15:22');--> 7 min (15:15:22 - 15:08:22)
insert into sessions values (3,'2020-02-20 15:08:22');
insert into sessions values (3,'2020-02-20 15:15:22');--> 7 min
insert into sessions values (3,'2020-02-20 15:20:22');--> 5 min

A: This shows you how you can accomplish that in mysql 5.x and higher
Please read the Text at the end for more information

CREATE TABLE IF NOT EXISTS `sessions` (
    id_user int,
    `start_date` datetime
);

insert into `sessions` values (1,'2020-02-21 08:24:07');
insert into `sessions` values (1,'2020-02-21 08:24:08');
insert into `sessions` values (1,'2020-02-21 15:08:20');
insert into `sessions` values (1,'2020-02-21 15:08:21');
insert into `sessions` values (1,'2020-02-21 15:08:22');
insert into `sessions` values (2,'2020-02-20 15:08:22');
insert into `sessions` values (2,'2020-02-20 15:15:22');
insert into `sessions` values (3,'2020-02-20 15:08:22');
insert into `sessions` values (3,'2020-02-20 15:15:22');
insert into `sessions` values (3,'2020-02-20 15:20:22');

✓

✓

✓

✓

✓

✓

✓

✓

✓

✓

✓

SELECT
  IF(@iduser = id_user,TIME_FORMAT(TIMEDIFF(`start_date`,@date), '%H:%i:%S'), NULL) Datediff
  ,@iduser := id_user iduser
  , @date := `start_date` `start_date`
 FROM
  (SELECT * FROM sessions ORDER by id_user ASC, start_date ASC) t
  ,(SELECT @iduser := 0) a,(SELECT @date := 0) b;

Datediff | iduser | start_date
:------- | -----: | :------------------
null     |      1 | 2020-02-21 08:24:07
00:00:01 |      1 | 2020-02-21 08:24:08
06:44:12 |      1 | 2020-02-21 15:08:20
00:00:01 |      1 | 2020-02-21 15:08:21
00:00:01 |      1 | 2020-02-21 15:08:22
null     |      2 | 2020-02-20 15:08:22
00:07:00 |      2 | 2020-02-20 15:15:22
null     |      3 | 2020-02-20 15:08:22
00:07:00 |      3 | 2020-02-20 15:15:22
00:05:00 |      3 | 2020-02-20 15:20:22

db<>fiddle here
It uses TIMEDIFF to get the Difference between to rows.
And the uses TIME_FORMAT to get rid of the milliseconds.
The new Datediff column is at the start and must stay there so that the Algorithm can work. If you want to reorder it in mysql you need a new outer SELECT query.
The final problem with this algorithm is, that it simple makes time1 - time2, it doesn't care if a new day start, it would still make this for every id_user. It is possible to use a much more sophisticated ORDER BY clauses.


text:
Q: Selenium webdriver not finding add to cart button in Amazon After selecting a product and opening it in another page Im not able to click on add to cart button in amazon using selenium.

A: If you are not switching to other page, Add to card option will not be located.
Switch to the opened page and then try to click on the button.
handles = driver.window_handles
driver.switch_to.window(handles[1])
driver.find_element_by_id("add-to-cart-button").click()

If you have done this, share the code you have tried and error you get.

A: Without HTML page you are trying to perform, it is difficult to pinpoint exactly. However, I would like to take a stab at it considering these:

*

*Click on product in home page

*Product opens in a new tab window

*Click on add to cart

P.S: I will write it using Java since you haven't mentioned on the language being used. Will be similar in others as well
Click on product in home page
List <Webelement> productCheck = driver.findElements(By.xpath("<xpath of the product>"))
if (productCheck.size() == 0){
// do something
else {
driver.findElement(By.xpath("<xpath of the product>")).click();
}

Product opens in a new tab window and  Click on add to cart
String parent = driver.getWindowHandle();
List<String> windows = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(windows.get(1));

// Inside the tab window

List <WebElement> addtoCartButton = driver.findElements(By.xpath("<xpath of Add to cart button>"));
if (addtoCartButton.size() == 0 ) {
// do something
else {
driver.findElement(By.xpath("<xpath of Add to cart button>")).click();
}

// do whatever you want in the new tab and if you want to switch back then:

driver.switchTo().window(parent);


text:
Q: why append(function()) return None after revealing the values? I got the result and then try to retrieve the values I got None values
I have defined a function who_score('d','g','sm',a,ch,sb) and then I want to use that function to make a new list based on if conditions. So, I made a loop to iterate over my data df_6_factors and append the result for each row in a new list called who_estimator
here is my code:
who_esimator = []     #the empty list
for i in range(10):
if df_6_factors.isnull().iat[i,0]  or df_6_factors.isnull().iat[i,1] or df_6_factors.isnull().iat[i,2] or df_6_factors.isnull().iat[i,3] or df_6_factors.isnull().iat[i,4] or df_6_factors.isnull().iat[i,5]:
    who_esimator.append('NaN')
else:
    if df_6_factors.iat[i,1] == 0:
        d = 'n'
    elif df_6_factors.iat[i,1] == 1:
        d = 'y'
    else:
        d = 'e'
    if df_6_factors.iat[i,2] == 0:
        g = 'm'
    elif df_6_factors.iat[i,2] == 1:
        g = 'f'
    else:
        g = 'e'
    a = df_6_factors.iat[i,3]
    if df_6_factors.iat[i,4] <=2:
        sm = 'n'
    else:
        sm = 'y'
    ch = df_6_factors.iat[i,5]
    sb = df_6_factors.iat[i,6]
    who_esimator.append(who_score(d,g,sm,a,ch,sb))

I got the output that I want as you see here:
15
2
6
4
7
40
20
6

but when I want to read the list who_esimator I got none value and 'NaN' value even though the data is not Null
[None, 'NaN', None, None, None, None, 'NaN', None, None, None]

I am a python self_learner and appreciate any help
Thanks


text:
Q: How to set up WCF transport security using Windows for clients and service for security newbie? I am pretty new to WCF services and especially to security - and am a bit overwhelmed by all the security options.
We are currently implementing a WCF service (both the service and clients) in an intranet running Windows machines. So I thought about using Windows credentials as transport security mechanism.
But I think I need some help on a few things:

*

*after adding the transport security settings in the config of the WCF service, the client config then contains after updating the service reference an element called userprincipalname. That confuses me as I thought the user would be the Windows user running the app, which calls the service, rather than some hardcoded value in the client config. So why is a user specified in the client config?

*and does Windows automatically pass the right user from the clients to the service or do I need to add any special code on the client side to "set" the right user? We would be calling the WCF service from a Windows Forms client.
(We will be self hosting the service in a windows service if it matters - for testing I run the service under my own account.)
Thanks all!

A: Have a look at this: http://msdn.microsoft.com/en-us/library/ms733089(v=vs.100).aspx
Has the configs for both, client and server.

A: This topic can be helpful for you:
http://social.msdn.microsoft.com/Forums/en/wcf/thread/0aac0110-187e-4a00-a597-f15b768cf16c


text:
Q: ranlib Error using Alire and GNAT with ASFML i am learning how to use Alire using the Ada binding to SFML which is ASFML. So far I have downloaded
and installed ASFML using Alire and have successfully imported it into my test project. When I go to compile it, it does compile and bind but gets stuck on the Linker phase.
Here is the error:
gprbuild -d -PC:\Users\Amynu\testproj\testproj.gpr -XASFML_BUILD_MODE=optimize -XASFML_CONTRACTS=enabled -XASFML_STYLE_CHECKS=enabled -XASFML_RUNTIME_CHECKS=enabled -XASFML_COMPILE_CHECKS=enabled -XOS=Windows_NT -XTESTPROJ_BUILD_MODE=optimize -XTESTPROJ_CONTRACTS=disabled -XTESTPROJ_STYLE_CHECKS=disabled -XTESTPROJ_RUNTIME_CHECKS=disabled -XTESTPROJ_COMPILE_CHECKS=disabled
Compile
   [Ada]          testproj.adb
Bind
   [gprbind]      testproj.bexch
   [Ada]          testproj.ali
Link
   [link]         testproj.adb
c:/gnat/2021/bin/../libexec/gcc/x86_64-w64-mingw32/10.3.1/ld.exe: C:\Users\Amynu\testproj\alire\cache\dependencies\asfml_2.5.2_b775db19\lib\libasfml.a: error adding symbols: archive has no index; run ranlib to add one
collect2.exe: error: ld returned 1 exit status
gprbuild: link of testproj.adb failed

I have absolutely no idea what a "ranlib" is, I searched Alire but it's not a known crate or a library. I tried various options in Alire such as
alr with libranlib

and
alr get ranlib

To no avail. Is it an option within GNAT's command line? I did look into the GPR file for the project and that all looks alright. One the GPR's being auto generated by Alire when I build the project with
alr init --bin testproj
alr cd testproj
alr with libasfml
alr build

I did a Google search and found a lot of solutions connected to Unix and IBM(?) something about ranlib being outdated as most compilers use "rm" now? I couldn't find a solution to GNAT flagging the same error.
Am I just using an outdated audio library?
Thanks in advance for any help :)

A: Thank you guys! That solved the problem. Now I am stuck with a loads of "undefined references to..." I actually went through all the source files and got rid of all the warnings by addIng Constant to most variable names. I am guessing it's looking for a dependency that is missing?
Build Libraries [gprlib] asfml.lexch [link library] libasfml.dll c:/gnat/2021/bin/../libexec/gcc/x86_64-w64-mingw32/10.3.1/ld.exe: C:\Users\Amynu\testproj\alire\cache\dependencies\asfml_2.5.2_b775db19\obj\sf-audio-music.o:sf-audio-music.adb:(.text+0x32): undefined reference to `sfMusic_createFromFile'

And about 15 lines under that with the same error type. After looking into it, I had a look a the lines of code the error were referring to and found the errors are referencing what look like external files? Is their a part of ASFML that didn't download with the library?

A: I scoured the code for the first linker error and found line it's referring to.
with Interfaces.C.Strings;

package body Sf.Audio.Music is
   use Interfaces.C.Strings;

   --//////////////////////////////////////////////////////////
   --/ Create a new music and load it from a file
   --/
   --/ @param Filename   Path of the music file to open
   --/
   --/ @return A new sfMusic object (NULL if failed)
   --/
   --//////////////////////////////////////////////////////////
   function CreateFromFile (Filename : String) return sfMusic_Ptr is
      function Internal (Filename : chars_ptr) return sfMusic_Ptr;
      pragma Import (C, Internal, "sfMusic_createFromFile");
      Temp : chars_ptr   := New_String (Filename);
      R    : sfMusic_Ptr := Internal (Temp);
   begin
      Free (Temp);
      return R;
   end CreateFromFile;

I cannot find the file it's trying to reference anywhere in the ASFML library. Was it left out?
So far, I have managed to successfully build ASFML in Alire with
alr get asfml
cd asfml
alr build asfml

This worked fine. Then I successfully imported into my project with
cd myproj
alr myproj with asfml

Again, do problems. Then I attempted to build it (after correcting the ranlib error) and I got the same load of linker errors. I don't understand why, as I successfully built the asfml library before I imported it wit Alire. Is it just a file I am missing, or do I have to explicitly tell the linker where the asfml file is?
Some of the errors.
Compile
   [Ada]          alicegame.adb
Build Libraries
   [gprlib]       asfml.lexch
   [link library] libasfml.dll
c:/gnat/2021/bin/../libexec/gcc/x86_64-w64-mingw32/10.3.1/ld.exe: C:\Users\Amynu\alicegame\alire\cache\dependencies\asfml_2.5.2_b775db19\obj\sf-audio-music.o:sf-audio-music.adb:(.text+0x32): undefined reference to `sfMusic_createFromFile'
c:/gnat/2021/bin/../libexec/gcc/x86_64-w64-mingw32/10.3.1/ld.exe: C:\Users\Amynu\alicegame\alire\cache\dependencies\asfml_2.5.2_b775db19\obj\sf-audio-soundbuffer.o:sf-audio-soundbuffer.adb:(.text+0x22): undefined reference to `sfSoundBuffer_createFromFile'


text:
Q: Java regexp: simplifying a reg exp I'm validating data.
For some fields, data can be expressed combining | and , char to separate a group of 1 or 2 digits.
The regexp doing that is expressed here.
For others fields, data can't mix both separators but must be one or the other.
So I modified the regexp here to validate such field (see https://regex101.com/r/FfvavR/8)
^[0-9]{1,2}(?:[,][0-9]{1,2})*$|^[0-9]{1,2}(?:[|][0-9]{1,2})*$

It works perfectly:
It accept:
1
10
1|5
0
1,2,3,0,2
00
00|11|22|33|44|55|66|77|88|99

And it refuse:
1,
10,,
1,2,3!5
1|100
1,2,3|5|10,20|30

Question
I wonder if the new regexp could be simplified though?

A: If you need a regex for this, you may use
^[0-9]{1,2}(?=([,|])|$)(?:\1[0-9]{1,2})*$

See the regex demo
Java:
String pat = "^[0-9]{1,2}(?=([,|])|$)(?:\\1[0-9]{1,2})*$";

If you are using it with matches, omit the leading ^ and trailing $.
Details

*

*^ - start of string

*[0-9]{1,2} - 1 or 2 digits

*(?=([,|])|$) - a positive lookahead that captures into Group 1 a , or | char or matches the end of string (so as to allow 1, 12, etc.)

*(?:\1[0-9]{1,2})* - zero or more consecutive repetitions of

*

*\1 - Group 1 text (the first separator)

*[0-9]{1,2} - 1 or 2 digits

*$ - end of string.

Java demo:
List<String> strs = Arrays.asList("1","10","1|5","0","1,2,3,0,2","00","00|11|22|33|44|55|66|77|88|99","1,","10,,","1,2,3!5","1|100","1,2,3|5|10,20|30");
        Pattern p = Pattern.compile("[0-9]{1,2}(?=([,|])|$)(?:\\1[0-9]{1,2})*");
        for (String str : strs)
            System.out.println(str + ": \"" + p.matcher(str).matches() + "\"");

Output:
1: "true"
10: "true"
1|5: "true"
0: "true"
1,2,3,0,2: "true"
00: "true"
00|11|22|33|44|55|66|77|88|99: "true"
1,: "false"
10,,: "false"
1,2,3!5: "false"
1|100: "false"
1,2,3|5|10,20|30: "false"

A: Simplified? Don't focus on the Regex only and use what Java offers you.
The more and more requirements and constraints you need to put on the Regex, the more likely you don't need one. Regex is good for the characters validation if matches the pattern correctly, not to validate against the exact range of numbers.
Since you have the valid format, parse the numbers from string to an array with | or , delimiter and validate. This is a correct, effective and straightforward way.
Regex is not the magic bullet for everything.


text:
Q: USB detection issues with Ubuntu 16.04 on Lenovo Yoga 300 I'm running Ubuntu MATE 16.04 on a Lenovo Yoga 300-11IBR and am having trouble with USB devices being detected.
The primary device in question is a Seagate Wireless Plus external hard drive. This particular drive has swappable interface boards (I'm using the USB3 one which it came with) and the interface board has an LED on it which provides an indication of whether it's going to work or not: if the LED lights when the drive is connected then it will be detected and work; if the LED doesn't light then it won't be detected (even by lsusb).
It appears to exhibit the same behaviour whether connected via USB3 or 2: when connected via USB3 it behaves as above; when connected via USB2 the LED either blinks (as the drive seems to require additional power via another USB cable - which I've lost - when connected via USB2) or doesn't light at all.
A reboot usually, but not always, fixes it: in cases where rebooting helps, the aforementioned LED lights as soon as the machine begins the POST sequence, or sometimes during the shutdown process.
This issue also seems to affect the SD reader: with a card inserted, it is only intermittently detected, so I assume that it is connected via USB internally.
Does anyone have any idea what might be going on and/or how to fix it?


text:
Q: Install alternate version of python2.7.9 on rhel7.2 RHEL7.2 comes with python2.7.5
I want to install an alternate version of 2.7 (2.7.9) but it keeps messing with my preinstalled version (since both are python2.7).
I run:
./configure --enable-shared LDFLAGS=-Wl,-rpath=/usr/local/lib/ --prefix=/usr/local/
make && make altinstall

the result is always /usr/bin/python2.7 being changed. Consequently, yum doesn't work anymore...
How do I install an alternate version of python without messing with the preinstalled python2.7 version?
On another issue, this build process that I inherited is using make -j2 -o2 but I couldn't find any reference to those flags on make. Does make support these flags (j2, o2)? What's their purpose?
EDIT
It appears that that wasn't the culprit.
In my build scripts, right after the installation I was using the following command:
grep "/usr/local/lib/" /etc/ld.so.conf || (echo "usr/local/lib/" >> /etc/ld.so.conf && /sbin/ldconfig)

That wasn't good as it always linked the python to the newly installed one.
Changing the line to the following fixed the problem:
grep "/usr/local/lib/" /etc/ld.so.conf || (echo "/usr/lib\n/usr/local/lib/" >> /etc/ld.so.conf && /sbin/ldconfig)

Now, python runs 2.7.5 and python2.7 runs 2.7.9
Regarding the flags on make, I still don't know what they do...