Posts

Showing posts from January, 2014

c# - How to do Recursice Funciton Return List<>? -

i trying playlist on youtube , using json http request. youtube playlist api supports max 50 results want make recursive funciton , funciton should return list. private async task<list<classes.playlist>> getplaylist(string id, string pagetoken = null) { string jsontext = await x.getjson(id, pagetoken); list<classes.playlist> list = new list<classes.playlist>(); if (jsontext == null) { return null; } else { jobject jsonobj = jobject.parse(jsontext); foreach (var item in jsonobj["items"]) { list.add(new classes.playlist { image = (string)item["snippet"]["thumbnails"]["default"]["url"], title = (string)item["snippet"]["title"], videoid = (string)item["snippet"]["resourceid...

wordpress - PHP and Shortcode Combination -

on website display social locker wordpress plugin around custom field. <?php echo do_shortcode('[sociallocker]'.$to_lock.'[/sociallocker]');?> here custom field <?php the_field('link'); ?> social locker requires open , close shortcode: [sociallocker id="16619"] [/sociallocker] the following not work correctly: <?php echo do_shortcode('[sociallocker id="16619"]'); ?> <?php the_field('link'); ?> <?php echo do_shortcode('[/sociallocker]'); ?> the function do_shortcode accept single shortcode, can't pass parts of shortcode (open tag, content, closing tag) separately. in case there opening , closing shortcode, should call following. <?php echo do_shortcode( '[s_tag]' . $content . '[/s_tag]' ); ?> so, you've update following lines <?php echo do_shortcode('[sociallocker id="16619"]'); ?> <?php the_field(...

sml - How to have more than one type in ML? -

is possible in ml allow variable in ml have more 1 type? for instance, if want node in tree int or string. node of int * string i tried results in tuple type of (int, string). don't want tuple, either int or string. allowed? as pointed out in comment, feature you're looking union types. believe syntax them in sml is: datatype node = intnode of int | stringnode of string

encoding - Javascript function to replace iso-8859-2 characters with utf8 characters -

i'm gathering data websites nodejs, request , cheerio, 1 site has iso-8859-2 charset , characters not appear correctly. i tried use iconv-lite, iconv.encode(str, "utf-8") or iconv.decode(str, "utf-8") gave me same output or hexadecimal value. plan create function replaces hungarian iso-8859-2 characters uft8 characters (since there few characters , of them has exact match except 2 has relative match). the first issue don't know how grab iso-8859-2 values. gave sample string contains (but not all!) values, i'm sure there's better solution. idea put iso-8859-2 charachters , utf-8 characters in array , use replace method change values. var teststring = "besz�ll�t�"; var = teststring.substring(4, 7); teststring = teststring.replace(a, "\xe1"); var = teststring.substring(7, 10); teststring = teststring.replace(i, "\xed"); var o = teststring.substring(9, 12) teststring = teststring.replace(o, "\xf3"); ...

django - Default image avatar depending on gender -

i create kind of profiles default avatars. gender_choices = ( ('m', 'male'), ('f', 'female'), ) class someone(models.model): name = models.charfield(max_length=120) gender = models.charfield(max_length=1, choices=gender_choices) image = models.imagefield(upload_to='avatars', default=someone_avatar) i'm trying write function returns path folder jpg. def someone_avatar(instance): gender = instance.gender if gender == 'male': avatar = 'avatars/m.jpg' else: avatar = 'avatars/f.jpg' return avatar obviously doesn't work, give me advise how solve it? maybe should overwrite save method? thx. edited ok, tried post_save does't work well: def set_avatar(instance): avatar = instance.image gender = instance.gender if gender == 'male': avatar = 'persons/m.jpg' else: avatar = 'persons/f.jpg' retur...

android - I want to add a progress dialog -

i want add progress dialog. want add error internet connection . how do. happy if write clearly. it's mine fragment activity turkish: eğer bizimkilerden biri okuyorsa şöyle diyim hani webview hazırlandığında yuvarlak bişey dönüyor ya ondan olsun istiyorum birde internet yoksa bağlantı yok hatası istiyorum my xml <framelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.kamubilgi.kamu_bilgi.ekran2"> <!-- todo: update blank fragment layout --> <webview android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/webview3" /> </framelayout> my fregment activity package com.kamubilgi.kamu_bilgi; import android.os.bundle; import andr...

Exporting logs from Snort to Syslog-ng to Redis -

i using snort 2.9.3 , export logs syslog-ng, , syslog-ng redis database. found plugin: syslog-ng-mod-redis however, include this? how can confirm logs produced snort can read syslog-ng? i using ubuntu 16.04 if install plugin, loaded automatically. can check following command: syslog-ng -v on ubuntu syslog-ng confined apparmor. check security logs, , if see access denied, add rule apparmor able read snort logs.

archive - how can i read a .txt file separated by commas in C? -

i'm having lot of problems doing task. have txt 1 line of words separated commas. have read , put in array. far tried using strtok() gives me errors. here's code: #include<stdio.h> #include<string.h> #include<stdlib.h> #include<omp.h> int main(){ char string[5000],list[200],*token,s=", "; int i; file *lista; lista=fopen("lista.txt","r"); i=0; token=strtok(string,s); strcpy(list[i],token); while(fscanf(lista,"%s",string)!=eof){ token=strtok(null,s); strcpy(list[i],token); i=i+1; } fclose(lista); } it gives me the" expectig char *restrict" error i'm out of ideas. btw: i'm in linux there many strange things in code, guess, want this: char string[5000], *list[200], *token; char * s = ","; int i; file *lista; lista = fopen("c:\\file.txt", "r"); int max_file_size = 1000; char * buffer = (char*)malloc(s...

How do I use .NET DLLs outside GAC in PHP -

i little bit confused fact php can use dll files dotnet object global assembly cache , not local folder (from know). how site, that's using dll, going work, when web server doesn't have such gac? right developing on local machine; no problem, worried if able run site elsewhere. so question is: possible access dll location gac? i have seen quite lot questions/answers already, of them relating asp.net , how use dlls in visual studio. thanks in advance -snrk edit: describe want "lac" (local assembly cache).

ember.js - Ember js firebase upload error to upload file -

i have problem @ moment of wanting files firebase throw following error, not understand because tells me add in mirage / config not use that. assert.js:36 mirage: ember app tried post ' https://firebasestorage.googleapis.com/v0/b/ember-firebase- ****.appspot.com/o?name=images%2fbacul-anuncio.png', there no route defined handle request. define route matches path in mirage/config.js file. did forget add namespace? este es mi componente donde tengo la logica de subir los datos firebase this component have logic upload data firebase import ember 'ember'; export default ember.component.extend({ /* esto es para subir imagenes declaramos algunas variables */ firebaseapp: ember.inject.service(), storageref:'', file: '', /* fin */ btn_label:'guardar', actions:{ click_btn_save(param){ // create metadata var metadata={ contenttype: 'imag...

mysql - Getting an item count and joining table to display items customer detail -

i have 2 tables: customers items i need display query shows each customers (selling) items total example: customer_name | total_items_customer_selling | customer_address i have used count() keep getting total value items in table select count(id) items group items.id also how join ? hope that's specific enough structure: customers(id(primary), name, address, city, state). items(id(primary), description, cost, seller(fk)) hope explains structure better select c.id, c.name, count(*) items customers c left join items on i.seller = c.id group c.id, c.name

aframe - Why is my screen blank in A-Frame? -

i opened a-frame scene both using hello world codepen , boilerplate, blank white screen in chrome. i found solution here .it works me. details below: chrome first, enable hardware acceleration: go chrome://settings click + show advanced settings button in system section, ensure use hardware acceleration when available checkbox checked (you'll need relaunch chrome changes take effect) enable webgl: go chrome://flags ensure disable webgl not activated (you'll need relaunch chrome changes take effect) inspect status of webgl: go chrome://gpu inspect webgl item in graphics feature status list. status 1 of following: hardware accelerated — webgl enabled , hardware-accelerated (running on graphics card). software only, hardware acceleration unavailable — webgl enabled, running in software. see here more info: "for software rendering of webgl, chrome uses swiftshader, software gl rasterizer." unavailable — webgl not available in hardware or software....

c# - How to play an attack animation plus adding a certain amount of damage -

Image
i've been trying put 1 attack animation working , playing non-stop instead of playing when press left-shift. for now, have. set null state or idle in controller , make sure it's base state, create parameter trigger name attack, drag animation controller , transition base attack anim parameter attack , transition back. in code on shift press write anim.settrigger ("attack"); also if u haven't referenced animation either draging in variable or getcomonent ref wont work :)

amazon web services - AWS ELB Nginx Remote Address -

i using nginx behind aws elb. when response server remote address of elb not of server possible have server ip instead of aws elb. no can't, if would contradict whole point of elb, , expose ec2 instance outside traffic. in case elb won't able balance load on instance , cause crash. if want access instance ip directly, don't use elb.

python - Getting next two indexes regardless of current index -

i trying create mock rock, paper, scissors game each name having 2 enemies, must able grab values of names regardless of position. say given list: names = ["kings", "queens", "jacks", "jokers", "masons", "warriors", "soldiers"] and trying use logic indexes being values , gather next 2 values of indexes. each index return these values. 0 - 1, 2 1 - 2, 3 2 - 3, 4 3 - 4, 5 4 - 5, 6 5 - 6, 0 6 - 0, 1 so 'warriors' have enemies of: soldiers , kings below being current implementation: def state_to_text(self): names = ["kings", "queens", "jacks", "jokers", "masons", "warriors", "soldiers"] if self.state == 0: return str(names[1], names[2]) if self.state == 1: return str(names[2], names[3]) if self.state == 2: return str(names[3], names[4]) if self.state == 3: return str(names[4...

c++ - reversing a vector and printing it -

how reverse vector? i've read lot of online post can't find 1 using namespace std. need use reverse() , vect.reverse(); here code: #include <iostream> #include <vector> #include <iomanip> using namespace std; int main() { cout << "kaitlin stevers" << endl; cout << "exercise 11 - vectors" << endl; cout << "november 12, 2016" <<endl; cout << endl; cout << endl; int size; cout << " how many numbers vector hold? " << endl; cin >> size; vector<int> numbers; int bnumbers; (int count = 0; count < size; count++) { cout << "enter number: " << endl; cin >> bnumbers; numbers.push_back(bnumbers); // adds element numbers } //display numbers stored in order cout << "the numbers in order are: " << endl; for(int bcount = 0; bcount ...

Nuget.exe pack WARNING: Description was not specified. Using 'Description' -

i'm trying create nuget package via command line , can't seem figure out how set description, author, title, summary, releasenotes, , owner. package creates gives me warning: warning: description not specified. using 'description'. warning: author not specified. using 'user'. here's command: nuget.exe pack "<myprojectpath>.csproj" -outputdirectory "<myoutputdirectory>" -properties configuration=release;description="mydescription";authors="mememe...metoo";title="mytitle";summary="mysummary";releasenotes="mychanges;"owners="mycompany" i'm not sure if matters i'm using nuget.exe came "credentialproviderbundle.zip" file downloaded visual studio team services. there's nothing wrong command. it not possible question asks without prerequisites. there must *.nuspec file in same directory *.csproj same exact name. the *.nuspec ...

python - Grab file from Desktop in Django Shell -

i have app named cars inside django project has utils.py file contains various utility methods used application. 1 of them (grab_new_models) used process csv file that's picked via periodic tasks fetches file remote location. method passed csv file method looks like def grab_new_models(csv_file): right i'm trying update code new functionality , having issues testing locally. using django shell, can't figure out how pass file method test it. have copy of csv file on desktop. how call method django shell , pass local csv file? so on django shell, python shell imports. can import util , call function. below provide simple example, reads simple file desktop , prints it: method: def grab_new_models(csv_file): open(csv_file) f1: = f1.read() print(a) execution: grab_new_models(r'c:\users\l3\desktop\learn_note.txt')

ASP.NET C# my rowcommand event fires but doesn't show the information -

well problem have gridview inside of content template of update panel, gridview have textboxes headers serve filtering system grid, , button allows select item gridview , display in fields, note fields capable of adding , modifying items in database, , autoupdate grid after it, have tested adding of new element, , work, point need select item list modify it, when try select one, button have each row, executes rowcommand doesn't show of information in textboxes, when click on adding button ("agregar") shows info., don't know why keep happening. great! this asp page: <%@ page title="" language="c#" masterpagefile="~/masterpage.master" autoeventwireup="true" codebehind="agregarcategoria.aspx.cs" inherits="legalcaseweb.agregarcategoria" %> <%@ register assembly="ajaxcontroltoolkit" namespace="ajaxcontroltoolkit" tagprefix="ajaxtoolkit" %> <asp:content id="...

apache spark - Does DStream's RDD pull entire data created for the batch interval at one shot? -

i have gone through this stackoverflow question, per answer creates dstream 1 rdd batch interval. for example: my batch interval 1 minute , spark streaming job consuming data kafka topic. my question is, rdd available in dstream pulls/contains entire data last 1 minute? there criteria or options need set pull data created last 1 minute? if have kafka topic 3 partitions, , 3 partitions contains data last 1 minute, dstream pulls/contains data created last 1 minute in kafka topic partitions? update: in case dstream contains more 1 rdd? a spark streaming dstream consuming data kafka topic partitioned, 3 partitions on 3 different kafka brokers. does rdd available in dstream pulls/contains entire data last 1 minute? not quite. rdd only describes offsets read data when tasks submitted execution. other rdds in spark only (?) description of , find data work on when tasks submitted. if use "pulls/contains" in more loose way express @ point record...

ruby - Split string variable into an array -

just wondering how split string variable letter letter , make array my word variable randomly selected word array of words: word = $file_arr[rand($file_arr.length)] how split word individual letters , add them array? example: if word pulls word "hello" $file_arr how make array like: ["h", "e", "l", "l", "o"] out of word variable all i've been able find online people doing strings type in , splitting on comma, how variable? use string#chars http://ruby-doc.org/core-2.0.0/string.html#method-i-chars 2.3.1 :009 > "hello world".chars => ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

java - What's wrong with overridable method calls in constructors? -

i have wicket page class sets page title depending on result of abstract method. public abstract class basicpage extends webpage { public basicpage() { add(new label("title", gettitle())); } protected abstract string gettitle(); } netbeans warns me message "overridable method call in constructor", should wrong it? alternative can imagine pass results of otherwise abstract methods super constructor in subclasses. hard read many parameters. on invoking overridable method constructors simply put, wrong because unnecessarily opens possibilities many bugs. when @override invoked, state of object may inconsistent and/or incomplete. a quote effective java 2nd edition, item 17: design , document inheritance, or else prohibit it : there few more restrictions class must obey allow inheritance. constructors must not invoke overridable methods , directly or indirectly. if violate rule, program failure result. superclass constru...

Converting Linq toDictionary C# -

im new c# , linq , im getting "system.invalidcastexception" when im trying make dictionary out of linq this object public class pdv { public datetime fecha { get; set; } public string clave_pdv { get; set; } public string nombre_pdv { get; set; } public string turno { get; set; } public string nombre_turno { get; set; } public int platillo { get; set; } public string nombre_platillo { get; set; } public int cantidad { get; set; } public double precio { get; set; } public double total { get; set; } } this code: var dishesgrouping = db_pdv.pdv.groupby(d => new { d.clave_pdv, d.nombre_pdv, d.turno, d.nombre_turno, d.platillo, d.nombre_platillo, d.precio }); var dishgroupingdictionary = dishesgrouping .todictionary(dishgrp => dishgrp.key, dishgrp => { var dishdictionary = new dictionary<int, int>(); (int = 1; <= 30; i++) ...

A Database Error Occurred - codeigniter -

i got error : unable connect database server using provided settings. filename: c:/xampp/htdocs/soheil/system/database/db_driver.php line number: 436 but when add below code inside database.php prints ok : echo '<pre>'; print_r($db['default']); echo '</pre>'; echo 'connecting database: ' .$db['default']['database']; $dbh=mysql_connect ( $db['default']['hostname'], $db['default']['username'], $db['default']['password']) or die('cannot connect database because: ' . mysql_error()); mysql_select_db ($db['default']['database']); echo '<br /> connected ok:' ; die( 'file: ' .__file__ . ' line: ' .__line__); my config : $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => '', 'password...

MySQL Connector C++ Unresolved External Symbol -

i'm working on project in vs 2013 community edition. uses mysql connector c++. here's code: database.cpp: #include "database.h" #include "common.h" #include <iostream> //this function used connect mysql database void database::connect() { config::loadconfig("config.ini"); mysqlsettings settings = config::getmysqlsettings(); sql::driver *driver; sql::connection *con; sql::statement *stmt; sql::resultset *res; //creates connection mysql server driver = get_driver_instance(); con = driver->connect("tcp://" + settings.host + ":3306", settings.username, settings.password); //connect lur database con->setschema(settings.database); } database.h: #pragma once #include "mysql_connection.h" #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> class database { public...

encryption - How to get RSA Public Key and Private Key and get the modulus and exponent in plain text? -

i kinda new cryptography, , requirement needs me "create or retrieve user’s rsa-oaep key. there should 1 public/private key pair each user device" and send server in form: {"modulus":"qmbrpdyray5ammo31neruizh5sbwegusmh4wlk6ujeidl+kwtlrone34kofexetbjsx0wygpi+vwl0ynq7buimukpytossaawut5kho3cqjxtk7g2gnepnuuxhiexggnrlzcslv8yilfvalhorwyc67kol+a+3tanq3h+bhewhm=","exponent":"aqab"} i tried openssl commands generate rsa public/private key pair, , comes out this: public key (have changed value bit security): ssh-rsa aaaab3nzac1yc2eaaaadaqabaaabaqc4nmwqhswk6py+n1olpbn3jelqedz8ywsn4j1kvp5hk+ps/5gcabkx/89budhhtkvz8mfsnkhkhu2wubpiikgavekbbbq8dhkubha07x1xtgy+qmyxtlahnaec6ooi6bixpfo6qam+snqxbwuvdpbzgqss+/p5r7aydlbalkoz+dzpbbahiik72c+xqcl8oofz4qqsvmakdkq+fvdm1e8u2ak4ygholeqjgcl8+xh7tfjsvuofsgsmlz2fmnxwhcyudokglp8zuvmuiaw9kejafta4xef3bbgrdyss7mlqf5/rhbpzyenwq1rvp8bhtumpqytqjzshuj8da3oqmfur xyz@xyz.xyz private key (have altered va...

javascript - Converting Bootstrap 3 remote modal to Bootstrap 4 modal with parameters -

so in near future shop going upgrade bootstrap 4 cannot until solve issue using remote modals. here example of how load our modals. reason use remote modals because modal-body dynamic , may use different file based on url. have heard using jquery("#newsmodal").on("load",..) alternative how this? found this not sure how anchor , how build url load remote data. global php include file: <div id="newsmodal" class="modal fade" tabindex="-1" role="dialog" data- ajaxload="true" aria-labelledby="newslabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 class=...

crash - Why Cassandra crashes after a rebuild? -

we have cassandra cluster of 9 nodes, 500g data in each node. 1 of nodes down while, , had rebuild data. the node octa-core hyper threads , 40g ram + 40g swap, , cassandra allowed 28g heap 800m young generation heap, , 10g row caches. g1 used garbage collection default cassandra settings it. with these settings, rebuild operation took day receive data other nodes. after while building secondary indexes on tables, cassandra crashed outofmemoryerror. what causing cassandra crash? seemed there enough memory during operation long monitoring it. what settings fix perform complete rebuild possible? thanks in advance.

ruby on rails - Scope conditionals for count? -

how can scope work multiple .count ? scope :level_5, -> { (self.accomplished.key.count > 4) && (self.accomplished.adventure.count > 2) && (self.accomplished.health.count > 2) && (self.accomplished.work.count > 2) } i've tried: scope :level_5, -> { self.accomplished.key.count > 4, self.accomplished.adventure.count > 2, self.accomplished.health.count > 2), (self.accomplished.work.count > 2) } or scope :level_5, -> { accomplished.where(key.count > 4, adventure.count > 2, health.count > 2, work.count > 2) } or scope :level_5, -> { "user.accomplished.key.count > 4" && "user.accomplished.adventure.count > 2" && "user.accomplished.health.count > 2" && "user.accomplished.work.count > 2" } it used conditionals if :level_5 trigger x.

lambda calculus - Haskell AST with recursive types -

i'm trying build lambda calculus solver, , i'm having slight problem constructing ast. lambda calculus term inductively defined as: 1) variable 2) lambda, variable, dot, , lambda expression. 3) bracket, lambda expression, lambda expression , bracket. what (and @ first tried) this: data expr = variable | abstract variable expr | application expr expr now doesn't work, since variable not type, , abstract variable expr expects types. hacky solution have: type variable = string data expr = atomic variable | abstract variable expr | application expr expr now annoying since don't atomic variable on own, abstract taking string rather expr. there way can make more elegant, , first solution? your first solution erroneous definition without meaning. variable not type there, it's nullary value constructor. can't refer variable in type definition can't refer value, true , false or 100 . the second solution in fact dir...

python - SciKit-learn grid search own scoring object syntax -

i want search hyper-parameters in convolutional net built keras. using kerasclassifier , gridsearchcv scikit-learn in line intro given here machinelearningmastery . typically scikit-learn optimizes on 'accuracy' , network runs image segmentation optimizing jaccard index. need define own scoring object grid search using make_scorer explaned here make_scorer , here defining scoring strategy . code section below shows implementation, getting error in model.compile(optimizer=optimizer, loss=eval_loss, metrics=(['eval_func']) , not know specify in metrics. default 'accuracy' assume in case 'eval_func' (which works when not doing grid search) or 'score' neither of these works in case. what right syntax? def eval_func(y_true, y_pred): '''evaluation function dice or jaccard, set global var jaccard=true''' if jaccard: return jaccard_index(y_true, y_pred) else: return dice_coef(y_true, y_pred)...

angularjs - Datetime range custom filter not working -

i trying filter list time frame. using angularjs, bootstrap datetimepicker , moment.js. happens not able list data. without custom filter able show list , simple text filter search. have added code related custom filter. code related filter in controller app.controller('reportcontroller', ['$scope', 'report','$filter', function($scope, report, $filter){ var self = this; $filter('myfilter')(datefrom ,dateto); app.filter('myfilter', function() { return function(items, from, to) { var result = []; (var i=0; i<items.length; i++){ var test = new date(items[i].datetime.$date); var month = test.getmonth()+1; var date = test.getdate(); var year = test.getfullyear(); var hour = test.gethours(); var minute = test.getminutes(); var second = test.getseconds(); var newdat...

Declare type list argument in F# -

i building simple function compares 2 lists , returns true if first list prefix of second one. expected signature: prefix: int list -> int list -> bool for example: prefix [1; 2] [1; 2; 3; 4] --> true prefix [ ] [1;2] --> true prefix [2] [1;2;3] --> false right now, @ step: let prefix l1 l2 = match l1 | (l1, l2) when (l1.[0] = l2.[0]) -> true | _ -> false i think on right way, got error: operator 'expr.[idx]' has been used on object of indeterminate type based on information prior program point. consider adding further type constraints how can declare in prefix l1 , l2 lists? looked solution here problem trivial there not answer. to answer last part of question declaring types lists (since other parts answered already), use "type annotations". (name : type) in function argument, such as let prefix (l1 : _ list) (l2 : _ list) = ... that declare both l1 , l2 lists of type c...

ios - array items not saved properly in core data entity -

Image
i have problem last item of string array saved in required core data entity. i have multi-dimensional array called "itemnames". flatmap array simple one-dimensional array iterate through it. loop creates every item newitem saved in core data entity "calc_values" in attribute "calc_item". the console output newitem looks aspected. however, when load core data entry entity "calc_values", receive console output 2. shows me last item, "item9" saves in according entity (cf. console output 2). what have change code save items when iteration through array? code (swift 3): let context = (uiapplication.shared.delegate as! appdelegate).persistentcontainer.viewcontext var calc_values = [calc_values]() let itemnames = [["item1", "item2", "item3", "item4", "item5"], ["item6", "item7", "item8", "item9"]] //----------- sav...