text
stringlengths
64
89.7k
meta
dict
Q: Black screen after modifying index.js I am following a tutorial online to learn how to use React. The instructor made me create a project called albums and modify the content of index.js, however I get a black screen on the ios simulator. What I did (following the instructor's details): 1) Create a new project react-native init-albums 2) Enter the project directory with cd albums 3) Run react-native run-ios 4) I can see on the simulator screen what is inside the file App.js (The initial screen of - I assume - any new React Native project). Press Cmd+R to reload, Cmd+D or shake for dev menu etc. 5) Delete the content inside index.js and replace it with: import React from "react"; import { AppRegistry, Text } from "react-native"; const App = () => { return <Text>Some Text</Text>; }; AppRegistry.registerComponent("albums", () => App); It should appear Some Text on the top left of the simulator BUT it does not. The screen is black. What am I doing wrong? A: You need to define a background color for you application. You should also import View from react-native import { AppRegistry, Text, View } from "react-native"; const App = () => { return ( <View style={{backgroundColor: 'white', flex:1}}> <Text>Some Text</Text> </View> ); }; The reason that it is black is because the in the AppDelegate.m the rootView backgroundColor has been changed in version 0.58.0 In prior versions it was rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; It is now the following in 0.58.+ rootView.backgroundColor = [UIColor blackColor];
{ "pile_set_name": "StackExchange" }
Q: mysql how can I query a database table by day and month and produce totals I have the following database table "id","date_occurred","country","town","quantity" "1","2012-06-01","England","Andover","82" "2","2012-06-01","England","Colchester","569" "3","2012-06-01","England","Farnham","1" "4","2012-06-01","England","England","4" "5","2012-06-01","England","America","13" "6","2012-06-01","America","England","114" "7","2012-06-02","England","Andover","4" "8","2012-06-02","England","Colchester","207" "9","2012-06-02","America","England","14" "10","2012-06-03","England","Andover","3" "11","2012-06-03","England","Colchester","72" "12","2012-06-03","England","America","1" "13","2012-06-03","America","England","15" "14","2012-07-04","England","Andover","1" "15","2012-07-04","England","Colchester","309" "16","2012-07-04","England","America","4" "17","2012-07-04","America","England","11" "18","2012-08-05","England","Andover","2" "19","2012-08-05","England","Colchester","319" "20","2012-08-05","England","Farnham","1" "21","2012-08-05","England","America","4" "22","2012-08-05","America","England","25" "23","2012-08-06","England","Andover","93" "24","2013-06-06","England","Colchester","542" "25","2013-06-06","England","Farnham","1" "26","2013-06-06","England","England","4" "27","2013-06-06","England","America","7" "28","2013-06-06","America","England","115" I would like to produce the following output from a query Total sales per day per country for a given month 2012-06-01 England 669 2012-06-01 America 114 2012-06-02 England 211 Total sales per day per town for a given month 2012-06-01 Andover 82 2012-06-02 Andover 4 I have been trying various queries with group by, sum, and count, but can't get the correct output. any simple solutions or guidance welcome. Thanks in advance A: Try this: Total sales per day per country for a given month: SELECT date_occurred, country, SUM(quantity) FROM tableA WHERE YEAR(date_occurred) = 2013 AND MONTH(date_occurred) = 6 GROUP BY date_occurred, country Total sales per day per town for a given month: SELECT date_occurred, town, SUM(quantity) FROM tableA WHERE YEAR(date_occurred) = 2013 AND MONTH(date_occurred) = 6 GROUP BY date_occurred, town
{ "pile_set_name": "StackExchange" }
Q: Order in entity_load I see Documentation of entity_load but I didn't find anything about ordering of results, How can I order the results entity_load by delta? as example I fetch all product of one node by $node = node_load(313); $field = field_view_field('node', $node, 'field_product_select'); $pids = array(); foreach ($field['#items'] as $key => $value) { $pids[] = $value['product_id']; } $products = entity_load('commerce_product', $pids, array(), TRUE); $return = array(); foreach ((array) $products as $key => $product) { $return[$key]['product_id'] = $key; $return[$key]['product_type'] = $product->type; if($product->field_is_selected_price['und'][0]['value']) $selected_price=$product->commerce_price['und'][0]['amount']; $return[$key]['price'] = $product->commerce_price['und'][0]['amount']; $images = field_view_field('commerce_product', $product, 'field_product_images'); foreach ((array) $images['#items'] as $image) { $return[$key]['img'][] = $image['uri']; } } I want fetch products order by 'delta'(or other field ),(results are order by entity_id by default) , how can I achieve it? A: Most entity controller implementations of ::load() will return entities in the same order as the array of IDs passed in to be loaded. This is the case with DrupalDefaultEntityController and EntityAPIController, which are the two most common controllers. In this case you could structure your initial query to get a list of IDs to be loaded with EntityFieldQuery and then use the results of that to pass to entity_load. Looking at your original example, you just need to load a list of products based on the product field on a node. Here's a quick example of what it would take to handle that (since you don't need EntityFieldQuery): $node = node_load($nid); // If you don't already have access to the node $wrapper = entity_metadata_wrapper('node', $node); $product_ids = $wrapper->field_product_select->raw(); $products = entity_load('commerce_product', $product_ids); This works because the field data is always queried with order by delta when using Drupal core's field SQL storage: https://api.drupal.org/api/drupal/modules%21field%21modules%21field_sql_storage%21field_sql_storage.module/function/field_sql_storage_field_storage_load/7
{ "pile_set_name": "StackExchange" }
Q: pandas panel data update I am using panel datastructure in pandas for storing a 3d panel. T=pd.Panel(data=np.zeros((n1,n2,n3)),items=n1_label, major_axis=n2_label, minor_axis=n3_label) Later on, I am trying to update (increment) the values stored at individual locations inside a loop. Currently I am doing: u=T.get_value(n1_loop,n2_loop,n3_loop) T.set_value(n1_loop,n2_loop,n3_loop,u+1) My question- is this the simplest way? Is there any other simpler way? The following dont work: T[n1_loop,n2_loop,n3_loop] +=1 or T[n1_loop,n2_loop,n3_loop] = T[n1_loop,n2_loop,n3_loop] +1 A: TL;DR T.update(T.loc[[n1_loop], [n2_loop], [n3_loop]].add(1)) The analogous exercise for a DataFrame would be to assign with loc df = pd.DataFrame(np.zeros((5, 5)), list('abcde'), list('ABCDE'), int) df.loc['b':'d', list('AE')] += 1 df Exact pd.Panel analog generates an Error pn = pd.Panel(np.zeros((5, 5, 2)), list('abcde'), list('ABCDE'), list('XY'), int) pn.loc['b':'d', list('AE'), ['X']] += 1 pn NotImplementedError: cannot set using an indexer with a Panel yet! But we can still slice it pn = pd.Panel(np.zeros((5, 5, 2)), list('abcde'), list('ABCDE'), list('XY'), int) pn.loc['b':'d', list('AE'), ['X']] <class 'pandas.core.panel.Panel'> Dimensions: 3 (items) x 2 (major_axis) x 1 (minor_axis) Items axis: b to d Major_axis axis: A to E Minor_axis axis: X to X And we can use the update method pn.update(pn.loc['b':'d', list('AE'), ['X']].add(1)) Which we can see did stuff if we use the to_frame method pn.to_frame().astype(int) OR pn.loc[:, :, 'X'].astype(int).T YOUR CASE This should work T.update(T.loc[[n1_loop], [n2_loop], [n3_loop]].add(1))
{ "pile_set_name": "StackExchange" }
Q: Node + Mailchimp NPM: How to add a subscriber to a list and include their first and last name? Mailchimp is almost a perfect company, except their Node API documentation is non-existent. How can I add a subscriber to my new list and include their first name and last name? The code below successfully adds the subscriber, but first and last names are not being added. var MCapi = require('mailchimp-api'); MC = new MCapi.Mailchimp('***********************-us3'); addUserToMailchimp = function(user, callback) { var merge_vars = [ { EMAIL: user.email }, { LNAME: user.name.substring(user.name.lastIndexOf(" ")+1) }, { FNAME: user.name.split(' ')[0] } ]; MC.lists.subscribe({id: '1af87a08af', email:{email: user.email}, merge_vars: merge_vars, double_optin: false }, function(data) { console.log(data); }, function(error) { console.log(error); }); }; // addUserToMailchimp A: The supplied merge variables should be passed as a single object, not an array of objects. Please see my example below: var mcReq = { id: 'mail-chimp-list-id', email: { email: 'subscriber-email-address' }, merge_vars: { EMAIL: 'subscriber-email-address', FNAME: 'subscriber-first-name', LNAME: 'subscriber-last-name' } }; // submit subscription request to mail chimp mc.lists.subscribe(mcReq, function(data) { console.log(data); }, function(error) { console.log(error); }); It looks like you supplied your actual mail chimp API key in your question. If so, you should remove it immediately.
{ "pile_set_name": "StackExchange" }
Q: Summing up BigDecimal in a map of list of objects in Java I'm stuck with some elegant ways to get a summation of BigDecimals in a map. I know how to calculate the sum in a map of BigDecimal but not a List of object with a BigDecimal. The structure of my objects are as below: Class Obj { private BigDecimal b; // Getter for b, say getB() } Map<String, List<Obj>> myMap; I need to get a sum of all bs in myMap. Looking for some elegant ways to do this in Java, may be using streams? A: Stream the values of the Map. Use flatMap to flatten the stream of lists of BigDecimals to a stream of BigDecimals. Use map to extract the BigDecimals. Use reduce with a summing operation. BigDecimal sum = myMap.values().stream() .flatMap(List::stream) .map(Obj::getB) .reduce(BigDecimal.ZERO, (a, b) -> a.add(b) ); The Stream.reduce method takes an identity value (for summing values, zero), and a BinaryOperator that adds intermediate results together. You may also use a method reference in place of the lambda above: BigDecimal::add. A: BigDecimal sum = myMap.values() .stream() .flatMap(Collection::stream) .map(Obj::getB) .reduce(BigDecimal.ZERO, BigDecimal::add);
{ "pile_set_name": "StackExchange" }
Q: How to check for a certain value and then exchange to money values in Java? I was playing around with arrays and I wanted to create a program in which you enter the value of money and then check how many coins or bank notes you need to fill that value. In case you enter 650 you should get one for: 500 one for 100 and one for 50. That's the program I got so far, but somehow it only prints out all of the values stored in bankovci array. public static void main(String[] args) { int[]bills = {500,200,100,50,20,10,5,2,1}; int amount=Integer.parseInt(JOptionPane.showInputDialog("Vnesi znesek: ")); int sum=0; System.out.print("We will need bills for: "); while(sum<=amount) { for(int i=0; i < bills.length; i++) { if(amount-bills[i]>=0) { sum+=bills[i]; } else if(amount-sum>bills[i]) { i+=1; }System.out.print(bills[i]+", "); } }}} Edit In case I enter 650 or any other number I get the following output: We will need bills for: 500, 200, 100, 50, 20, 10, 5, 2, 1, A: There are cleaner ways of solving this problem (without using the break keyword), as I am sure other people will post. But to help you understand where you had trouble, here is a modified version of the code that you supplied. Notice that I changed the if statement, and removed the else block. I also had to add a break to exit the for loop early, which is what I think you were trying to use the i+1 for. public static void main(String[] args) { int[]bills = {500,200,100,50,20,10,5,2,1}; int amount=250; int sum=0; System.out.print("We will need bills for: "); while(sum<amount) { for(int i=0; i < bills.length; i++) { if(sum+bills[i] <= amount) { sum+=bills[i]; System.out.print(bills[i]+", "); break; } } }}
{ "pile_set_name": "StackExchange" }
Q: How to use '%%%' in a Build.scala file I'm getting familiar with using the '%%%' operator in a build.sbt file, but I don't understand how to use it in a build.scala file. I'm getting the following error: value %%% is not a member of String I'm guessing that I have to import the %%% somehow but I don't see how. I tried the following: import org.scalajs.sbtplugin.ScalaJSPlugin._ import ScalaJSKeys._ A: Edit: Since Scala.js 0.6.23, you need the following import: import org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._ Old answer for Scala.js < 0.6.23: As documented here, the appropriate imports are import org.scalajs.sbtplugin.ScalaJSPlugin import org.scalajs.sbtplugin.ScalaJSPlugin.autoImport._
{ "pile_set_name": "StackExchange" }
Q: How to change the start url phonegap duo to app setting? I'm new to using phonegap I want to create an android application using phonegap. I want to load different starting page that is when running the program for the first time I want to run URL1 (that allows the user to set app configs) and on subsequent runs I want to run URL2 (that loads the current settings) How can I do that?? A: You can use below code; if(first) super.loadUrl("URL1"); else super.loadUrl("URL2"); on your onCreate() method. Put the 'first' parameter in SharedPreferences as a flag to detect first run.
{ "pile_set_name": "StackExchange" }
Q: passing value to a dynamic created function in javascript I am having some problems while creating a dynamic webpage in javascript. My idea is to read a list of events and people signed up on them. I create a page with all events (each event is a button) and clicking on one of them, see the list of users. This works fine. But now, I am adding a button to export some of these users to an excel file. And I want to add a button with an onClick function like this: ...onclick=functionÇ(id_Event, numberOfUsers, listOfUsers)... Inside of the html code generated by javascript. I found some problems also doing like this so I changed so: var td = document.createElement("td"); var input = document.createElement("input"); input.setAttribute("type","button"); input.setAttribute("value","Exportar a Excel CSV"); input.onclick = function() { saveExcelFunctionControl(arrayNumberUsersInEvents[i], response); }; td.appendChild(input); document.getElementById("added"+element[i].id_Event).appendChild(td); I created a global array called arrayNumberUSersInEvents in which I am adding in each possition, people subscribed. i, is the id counter for each position. But even this, I am getting an undefined while reading the value of the firsdt parameter. I think it is a problem of dynamic data, I am not executing the function I want to each time I click the button. Do you know how to do something like this? To sum up: My problem is that I want to pass some arguments to a function in a dynamic created page. I don't know how to pass the data and read the correct parameters inside. I added my code because one user asked for it: for(i = 0; i < element.length; i++){ $(".eventsControl").append( '<li id="listControl'+ element[i].id_Event +'">'+ '<a href="#EventControl' + element[i].id_Event + '"' + 'data-transition="slidedown">'+ '<img class="crop" src= "' + element[i].image + '" />'+ '<h2>' + element[i].name + '</h2>'+ '<p>' + "Desc: " + element[i].description +'</p>'+ '</a>'+ '</li>' ).listview('refresh'); //console.log(response); //BUCLE for setting all users in each event. Better use some string and after, join all of them header = ' <div width="100%" data-theme = "e" data-role="page" id='+ element[i].id_Event + ' data-url="EventControl' + element[i].id_Event + '"> ' + ' <div data-theme = "a" data-role="header"><h1>Lista de Asistencia</h1> ' + ' <a href="#controlList" data-icon="back" data-iconpos="notext"></a></div>'+ ' <div data-role="content"> ' + ' <fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center">' + ' <div style="width: 500px; margin: 0 auto;">'; //header = header + '<input data-theme = "c" onclick="saveExcelFunctionControl(this)" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>'; eval('var numberUsers' +element[i].id_Event + "=1"); arrayNumberUsersInEvents[i] = 0; if(response.length>0){ bucle = ' <table width="100%" border="1" align="left"><tr>'+ ' <th>Nombre</th>'+ ' <th>Primer apellido</th>'+ ' <th>Segundo apellido</th>'+ ' <th>NIF</th>'+ ' <th>Asistencia</th>'+ ' </tr>'; for(iData = 0; iData < response.length; iData++){ if(element[i].id_Event == response[iData].id_Event){ //console.log(response[iData].name); bucle = bucle + '<tr><td>'+ eval('numberUsers' +element[i].id_Event) +'</td><td>'+ response[iData].name +'</td><td>'+ response[iData].surname1 +'</td><td>'+ response[iData].surname2 +'</td><td>'+ response[iData].NIF + '</td>'+ '<td> '+ '<input type="checkbox" id="checkBox'+element[i].id_Event+'_'+iData+'" name="option'+iData+'" value="'+iData+'"> '+ '</td>'+ '</tr>'; eval('numberUsers' +element[i].id_Event + "++"); arrayNumberUsersInEvents[i] = arrayNumberUsersInEvents[i]+1; } } //header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(\""element[i].id_Event "\","" + numberUsers + "\",\"" + response+ "\"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>'; //header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(""+numberUsers+"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>'; bucle = bucle + '</table>'; $("#controlList").after(header + bucle + '<div id=added'+element[i].id_Event+'></div>'); var td = document.createElement("td"); var input = document.createElement("input"); input.setAttribute("type","button"); input.setAttribute("value","Exportar a Excel CSV"); input.onclick = function() { saveExcelFunctionControl(arrayNumberUsersInEvents[i], response); }; td.appendChild(input); document.getElementById("added"+element[i].id_Event).appendChild(td); } } }, error: function(xhr, status, message) { alert("Status: " + status + "\nControlGetEventsRegister: " + message); } }); A: You can use closure to pass parameters to dynamically created onclick handler: input.onclick = (function() { var arr = arrayNumberUsersInEvents[i]; var resp = response; return function() { saveExcelFunctionControl(arr, resp); } })(); How do JavaScript closures work?
{ "pile_set_name": "StackExchange" }
Q: SVN info from ASP.NET : 'Can't determine the user's config path' Got an ASP.NET site which I wish to perform an SVN info call from. My understanding is this error message appears when a user hasn't yet done their basic setup to use SVN. Specifically there is a folder a few steps under AppData named Subversion which when not present and properly configured, shows the aforementioned message. The ASP.NET site is running under the account "NetworkService" whose AppData folder I cannot find. I was planning to copy & paste the Subversion folder, as it's not easy to do an actual log in as NetworkService. How can I proceed using NetworkService so that the "svn info" can also proceed? Thanks in advance-- FYI: Using SharpSvn as a wrapper. Doubt that matters, but there you go A: add this line before you authenticate and or perform any svn event. client.LoadConfiguration(Path.Combine(Path.GetTempPath(), "Svn"), true);
{ "pile_set_name": "StackExchange" }
Q: adb install system app I am aware that using adb install command installs an app in the /data/app folder. Also I know the in order to install an app as a system app I need to push it directly to the system. Is it possible to use adb install directly to the /system/priv-app/ on rooted phones? A: if I got your question, this should do the work: adb root adb remount adb push apk-filename-here /system/app/ adb shell chmod 644 /system/app/apk-filename-here adb reboot See this or this link for more info.
{ "pile_set_name": "StackExchange" }
Q: List all harddrives in a linux system I'm having problems to detect which one of my block devices is the hard drive. My system has a cd-rom drive, USB drives, and a single hard drive of unknown vendor/type. How can I identify the hard drive with a linux command, script, or C application? A: sudo lshw -class disk will show you the available disks in the system A: As shuttle87 pointed out, there are several other posts that answer this question. The solution that I prefer is: root# lsblk -io NAME,TYPE,SIZE,MOUNTPOINT,FSTYPE,MODEL NAME TYPE SIZE MOUNTPOINT FSTYPE MODEL sdb disk 2.7T WDC WD30EZRX-00D `-sdb1 part 2.7T linux_raid_member `-md0 raid1 2.7T /home xfs sda disk 1.8T ST2000DL003-9VT1 |-sda1 part 196.1M /boot ext3 |-sda2 part 980.5M [SWAP] swap |-sda3 part 8.8G / ext3 |-sda4 part 1K `-sda5 part 1.8T /samba xfs sdc disk 2.7T WDC WD30EZRX-00D `-sdc1 part 2.7T linux_raid_member `-md0 raid1 2.7T /home xfs sr0 rom 1024M CDRWDVD DH-48C2S References: https://unix.stackexchange.com/q/4561 https://askubuntu.com/q/182446 https://serverfault.com/a/5081/109417
{ "pile_set_name": "StackExchange" }
Q: Is it possible to add wildcards to @Query parameters? I've defined my ContactDao as follows: public interface ContactDao extends JpaRepository<Contact, Long> { /** * Finds all contacts that the given user has entered where the contact's full name matches {@code name}. * @param userId The current user's LDAP id. * @param name The name to search for. * @return A list of contacts matching the specified criteria. */ @Query(" select c from Form as f" + " inner join f.contacts as c" + " where f.requestorUserId = :userId" + " and lower(c.fullName) like lower(:name)" + " order by lower(c.fullName)") List<Contact> findUserContactsByUserIdAndName(@Param("userId") String userId, @Param("name") String name); } The above is working perfectly, and the SQL generated is what I'd write myself. The problem is that I'd like to add surrounding wild-cards to the :name parameter. Is there any nice way to do this? I've had a look at the Spring Data JPA reference document and I can't find anything regarding wildards and @query. The following hack works, but is a bit ugly: and lower(c.fullName) like '%' || lower(:name) || '%' Does anyone have a better solution? Thanks, Muel. A: I would also not call it a hack - it's the way JPQL syntax is defined for exactly these problems. However, there is an alternative using a CriteriaBuilder/CriteriaQuery, but maybe you find it even more complex (but you get compile-time type safety in return).
{ "pile_set_name": "StackExchange" }
Q: How to invoke functions of Smart Contract from Android phone? I deployed a smart contract with solidity along with a GUI by Javascript and HTML. This project works well on my computer. Now I want to invoke functions of Smart Contract from Android phone. Is there any possibility to do this? And if so, how to do? Ans also do I need to write my smart contract with Java ? or Solidity version is OK ? My solidity smart contract code : pragma solidity 0.4.23; contract RFID { struct StateStruct { bytes32 description; mapping(bytes32 => bytes32) sub_state; } struct ObjectStruct { StateStruct state; address owner; bool isObject; bytes32 review; } mapping(bytes32 => ObjectStruct) objectStructs; bytes32[] public objectList; event LogNewObject(address sender, bytes32 indexed id, bytes32 sub_states_types, bytes32 sub_states_values, address owner); event LogChangeObjectState(address sender, bytes32 indexed id, bytes32 sub_states_types, bytes32 sub_states_values); event LogChangeObjectOwner(address sender, bytes32 indexed id, address newOwner); event LogNewObjectReview(address sender, bytes32 indexed _id, bytes32 _review, address _owner); event LogChangeObjectStateReview(address sender, bytes32 indexed id, bytes32 _review); function isObject(bytes32 _id) public view returns(bool isIndeed) { return objectStructs[_id].isObject; } function getObjectCount() public view returns(uint count) { return objectList.length; } /*function setArraySize(uint256 _number_of_sub_states) public { number_of_sub_states = _number_of_sub_states; } function getArraySize() view public returns (uint256) { return number_of_sub_states; }*/ function newObject(bytes32 _id, uint256 number_of_sub_states, bytes32[10] sub_states_types, bytes32[10] sub_states_values, address _owner) public returns(bool success) { require(!isObject(_id)); uint256 counter=0; for(counter; counter < number_of_sub_states; counter++) { objectStructs[_id].state.sub_state[sub_states_types[counter]] = sub_states_values[counter]; emit LogNewObject(msg.sender, _id, bytes32(sub_states_types[counter]), bytes32(sub_states_values[counter]), _owner); } objectStructs[_id].owner = _owner; objectStructs[_id].isObject = true; objectList.push(_id); return true; } function newObjectReview(bytes32 _id, bytes32 _review, address _owner) public returns(bool success) { require(!isObject(_id)); objectStructs[_id].owner = _owner; objectStructs[_id].isObject = true; objectStructs[_id].review = _review; emit LogNewObjectReview(msg.sender, _id, _review, _owner); objectList.push(_id); return true; } function changeObjectState(bytes32 _id, uint256 number_of_sub_states, bytes32[10] sub_states_types, bytes32[10] sub_states_values) public returns(bool success) { require(isObject(_id)); uint256 counter=0; for(counter; counter < number_of_sub_states; counter++) { objectStructs[_id].state.sub_state[sub_states_types[counter]] = sub_states_values[counter]; emit LogChangeObjectState(msg.sender, _id, bytes32(sub_states_types[counter]), bytes32(sub_states_values[counter])); } return true; } function changeObjectStateReview(bytes32 _id, bytes32 _review) public returns(bool success) { require(isObject(_id)); objectStructs[_id].review = _review; emit LogChangeObjectStateReview(msg.sender, _id, _review); return true; } function changeObjectOwner(bytes32 _id, address _newOwner) public returns(bool success) { require(isObject(_id)); objectStructs[_id].owner = _newOwner; emit LogChangeObjectOwner(msg.sender, _id, _newOwner); return true; } } What I want to do is invoking functions of my contract by android phone. Note : I did sign up for Infura, however honestly I do not know how to use it on my android phone to invoke functions of this smart contract from my android phone ? A: Two things you need for this: Infura Web3js Infura will allow you to connect to the ethereum network (and is free). Then you can use web3 to interact with your contract. Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: Winforms-Timer : Started in asynch thread omits tick event in ui thread I had to implement two more asynch threads to my main ui thread. One ( T_A1 ) fetches some db data and returns, ui may still be active and recieve user interactions ( perhaps to change in the future back to one thread) and another thread ( T_A2 )which polls some hardware for a special value. I also have a timer on my winforms-ui, a simple windows.forms.Timer object. When T_A2 ( which is started in an own object ) throws an event to the ui thread to handle it, it is still in the asynch thread, but handled inside mainform. In this eventhandler I start the timer. ( Simply via timer.Start();) I logged the tick event, but I do not get it, it simply never occurrs, so I have no log entry. BUT when I start the timer with the help of Invoke/BeginInvoke I marshall the starting of the timer to be executed in the ui. AND then the tick event occurrs, and I get my log entry. My question is : WHY? If I do not use Invoke/BeginInvoke I start the timer in the thread, which throwed the event ( T_A2 ), so the tick would also be expected to occur in this thread, but the thread already died ? Or what could be the reason ? A: The why? is simple, threading is dangerous. It has a knack for not doing what you hope it will do. Many GUI classes in Winforms are not thread-safe, you must use Control.BeginInvoke to ensure that you modify their properties or call their methods on the exact same thread that created the objects. It is a pretty fundamental limitation, creating thread-safe code is difficult. Even simple classes in .NET are not thread-safe, none of the collection classes are. You have some latitude with, say, List<>, you can make it thread-safe yourself by carefully using the lock keyword to ensure that the List object is only ever accessed from a single thread. Still pretty hard to do correctly. That stops being practical when the class isn't simple and has non-trivial interactions with other classes and the operating system. Few classes in .NET are has heavy as Control, it has hundreds of methods and properties. So Microsoft itself just declared the job of making it thread-safe impossible, like they did with List<>, and there's no hope that you can add enough locking yourself to make it thread-safe. Deadlock is practically guaranteed. Nor did Microsoft give you enough access to the internals to inject the required locking, they didn't think it was worth it. So you must only ever use the objects from the same thread to keep it safe, they did give you the required tools to make that easy. Which includes BeginInvoke and all kinds of extra help like BackgroundWorker, TaskScheduler.FromCurrentSynchronizationContext and the async/await keywords. And the InvalidOperationException you get when you do it wrong, a very helpful exception. The specific implementation detail of the Timer class you ran into is that it is a pretty simple class and actually is thread-safe. Starting or stopping it on a worker thread works just fine and is a safe thing to do. Note that you didn't get the InvalidOperationException that you'd normally get when you violate threading requirements. Unfortunately, it depends on an implementation detail that you didn't take care of, and never would. Its Tick event is raised by a dispatcher loop, the kind you get from Application.Run(). And you didn't call Application.Run() on your worker thread. So the timer never ticks. The proper solution here is to not call Application.Run() on your worker, that's one solution that gives you two new problems. You already have a perfectly good thread that called Application.Run(). Use Control.BeginInvoke() to use it.
{ "pile_set_name": "StackExchange" }
Q: What "flavour" or type of LAN should I be using? I have Lubuntu 14.04 installed & running well on an old P4 machine (32 bit). I have Ubuntu 14.04 installed and running well, as a dual boot with WinXP, on a newer Core2Duo Asus MB system. Ubuntu is 64 bit - the WinXP is 32 bit. Each system is connected by Cat5 cable to the DSL router supplied by the Aliant (Bell) telephone company. (I have no information other than it is labelled "SpeedStream" and provides us with very slow "High Speed" 200Mb/s max). Both systems connect automatically to the Internet and seem to operate well. What I want to be able to do is transfer files between these two computers - nothing more. Can someone please tell me which type of LAN (eth0, DSL, IPv6, etc.,) I should configure? It would also be an enormous help if someone could tell me where and how to find ALL the necessary info to fill the boxes in Network Settings, etc. BTW when I run ifconfig I get 3 "paragraphs" - eth0, lo, ppp0 - and all are UP and seem to report no conflicts or problems. A: eth0 = Ethernet 0 = Wired connection ppp0 = Point-to-Point Protocol 0 = Connection to the Internet lo0 = Loop-back 0 = doesn't connect to any other computer then your own. Warning: All the below links are provided for documentation purposes only (a.k.a. RTFM). Don't install anything from these sites, just use the Ubuntu Software center! If you don't know anything about networking, the easiest to install would be the Very Secure File Transfer Protocol Daemon (Daemon = "server") For obvious reasons, you'd bind it to eth0 so it doesn't have to go all the way to the Internet to exchange files and you'd have to install it on both machines, turning them both into servers and would access the files from one of the clients to one of the servers with something like FileZilla The easiest to run would be Samba which turns your PCs into Windows-like servers, allowing you to use the file manager and to just browse files on the other machine (again: if you want both machines to be servers: install it on both.) However Samba would be a tiny bit more difficult to install. If I were you, I would start off with 1. and if you get fed up with having to go to FileZilla to exchange files, go on to 2. (or don't if you're happy with it)
{ "pile_set_name": "StackExchange" }
Q: perl regex period matches zero length character For example: $ perl -pe 's/(.)\G/{$1}/g' abcd and the result is: {}{a}{b}{c}{d} the first period(.) match is zero length. Is this a bug or a feature? A: For me the result is "abcd", because /(.)\G/g can never match — how can it match a single character before the current position, starting at the current position? s/\G(.)/{$1}/g on "abcd" produces "{a}{b}{c}{d}", which is expected.
{ "pile_set_name": "StackExchange" }
Q: JQuery UI datepicker how to show next prev arrows for month navigation? Exactly as the title says. When I load the datepicker there is nothing on the ends to click onto change month. But you can stil change the month just no visual?? A: Sounds like the graphics aren't being loaded properly. By default jQuery UI expects the folder with images to be a subfolder of the folder where the css file is. Use a tool such as firebug ('Net' tab) to detect the requests for the image with the arrows, and see what URL it's trying to load it from.
{ "pile_set_name": "StackExchange" }
Q: Casual English: Dropping the The Verb BE I heard the question: "What are you talking about?" frequently in American movies. However I notice they tend to drop the verb "are" and treat "y" as a vowel. The /t/ in the word "what" sounds like a flap t (tapped T). I'm not a native speaker and I'm trying to rely on my ears. I would like to know if my observation is correct. I would be grateful for any suggestion. A: I think this is the pronunciation that is sometimes written "What'cha talking about?" or "Whaddaya talking about?" (depending on the speaker's accent). If so, I think that most native speakers would consider the verb to still be there even though it has been almost completely swallowed. If you ask someone to repeat the question slowly they will likely either produce the verb ("What ... are ... you ..."), or keep it combined with the "what" ("Whadda ... ya ... talking ... about?"). But that could vary by dialect.
{ "pile_set_name": "StackExchange" }
Q: Use of dynamically created variables I have a button with a click event function as seen below. I want to be able to use different variables inside the function (nose2x, nose2y and so on), i.e the variable names are the same except for the numbers. I've tried build the variables like: 'AvGen.nose' + noseNr + 'Size' ... but it doesn't work. How could it be done? biggerNoseBtn.on('click', function() { if (AvGen.nose1Size <= 1.8) { AvGen.nose1x -= 3; AvGen.nose1y -= 3; AvGen.nose1Size = AvGen.nose1Size += 0.1; AvGen.nose1Size = Math.round(AvGen.nose1Size * 10) / 10; AvGen.nose1.transform('S' + AvGen.nose1Size + ', ' + AvGen.nose1Size + ', 0, 0, T' + AvGen.nose1x + ', ' + AvGen.nose1y); } }); A: Assuming AvGen is an object, you can use array notation to access its members. Try using this format: if (AvGen['nose' + noseNr + 'Size'] <= 1.8) { // other code... }
{ "pile_set_name": "StackExchange" }
Q: ComboBox not updating with Itemsource change My class Looks like this: Public Class CoursesLib Public CoursesOfferedMAIN As New Dictionary(Of String, Category) Public Class Category Private _CategoryName As String Private _Deleted As Boolean Public Courses As New Dictionary(Of String, Course) Public Function Contains(ByVal CourseName As String) For Each k As Course In Courses.Values If k.CourseName = CourseName Then Return True Exit Function End If Next Return False End Function End Class Public Class Course Private _CategoryName As String Private _CourseID As String Private _CourseName As String Private _Deleted As Boolean Public Sems As New Dictionary(Of String, Sem) End Sub Public Function Contains(ByVal find As String) For Each k As Sem In Sems.Values If k.SemName = find Then Return True Exit Function End If Next Return False End Function End Class End Class Following is the code i used for xaml in my wpf: <StackPanel Orientation="Horizontal" VerticalAlignment="Center" > <TextBlock Text="Categories" Margin="0,0,10,0" Width="100" VerticalAlignment="Center" /> <ComboBox Height="30" Name="CourseCategoryComboBox1" Width="120"> <ComboBox.ItemTemplate> <DataTemplate> <Label Content="{Binding CategoryName}" /> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> <Button Name="AddNewCourseCategoryButton" Background="Transparent" Content="Add New" Foreground="#FF0994EB"/> </StackPanel> <StackPanel Orientation="Horizontal" Name="NewCategorySubmitStackPanel"> <TextBlock Text="Name" Margin="0,0,10,0" Width="100" VerticalAlignment="Center" /> <TextBox Height="30" Name="NewCourseCategoryTextBox1" Width="120" MaxLength="25"/> <Button Name="SubmitNewCourseCategoryButton" Background="Transparent" Content="+" Margin="10,0,0,0" Foreground="#FF0994EB" FontWeight="Heavy" BorderBrush="Transparent" /> </StackPanel> <StackPanel Orientation="Horizontal" Name="CourseListStackPanel" > <TextBlock Text="Course" Margin="0,0,10,0" Width="100" VerticalAlignment="Center" /> <ComboBox Height="30" Name="CourseslistComboBox1" Width="120"> <ComboBox.ItemTemplate> <DataTemplate> <Label Content="{Binding CourseName}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> <Button Name="NewCourseButton" Background="Transparent" Content="Add New" Foreground="#FF0994EB"/> </StackPanel> <StackPanel Orientation="Horizontal" Name="NewCourseeSubmitStackPanel"> <TextBlock Text="Name" Margin="0,0,10,0" Width="100" VerticalAlignment="Center" /> <TextBox Height="24" Name="NewCourseeTextBox1" Width="120" MaxLength="25"/> <Button Name="SubmitNewCourseButton" Background="Transparent" Content="+" Margin="10,0,0,0" Foreground="#FF0994EB" FontWeight="Heavy" BorderBrush="Transparent" /> </StackPanel> The problem is when the add a new course to the collection, the combox is not updating, but when i restart the app, it gets added, it is not getting inserted when I complete the insert statement. Following is the code i use. Inserting and Updating the control: If Not NewCourseeTextBox1.Text = "" Then If Globals.Courses.CoursesOfferedMAIN(CType(CourseCategoryComboBox1.SelectedItem, WorkMateLib.CoursesLib.Category).CategoryName).Contains(NewCourseeTextBox1.Text) = False Then Dim c As New WorkMateLib.CoursesLib.Course c.Category = CType(CourseCategoryComboBox1.SelectedItem, WorkMateLib.CoursesLib.Category).CategoryName c.CourseID = DateTime.UtcNow.ToString() c.CourseName = NewCourseeTextBox1.Text c.Deleted = False Dim serv As New ServiceCourses.WCFCoursesClient Dim ex As String ex = serv.AddCourse(c) If ex = "1" Then NewCourseeTextBox1.Text = "" NewCourseeSubmitStackPanel.Visibility = Windows.Visibility.Collapsed Globals.Courses.CoursesOfferedMAIN(c.Category).Courses.Add(c.CourseID, c) CourseslistComboBox1.ItemsSource = Globals.Courses.CoursesOfferedMAIN(c.Category).Courses.Values Else MessageBox.Show(ex) End If End If End If Thank you. A: I tried a few methods and of them all following worked and is the easiest one as for me: The trick is to change the ItemSource Property to nothing first and then assigning the list or any other data source, this way, the Items are getting displayed right away without any problem. Example: Thank you for your time and help. SubjectlistComboBox1.ItemsSource = Nothing SubjectlistComboBox1.ItemsSource = Globals.Courses.CoursesOfferedMAIN(c.Category).Courses(c.CourseID).Sems(c.SemID).Subjects.Values
{ "pile_set_name": "StackExchange" }
Q: How can I count the number of pivot tables in an Excel workbook with VBA? How can I use VBA to count the total number of pivot tables in a workbook? A: I couldn't find an answer on StackOverflow so I wanted to share this. There is no native property that counts all pivot tables but there is a Worksheet.PivotTables.Count property. Loop through each sheet in a workbook and keep a running count like this: Public Function CountPivotsInWorkbook(ByVal target As Workbook) As Long Dim tmpCount As Long Dim iWs As Excel.Worksheet For Each iWs In target.Worksheets tmpCount = tmpCount + iWs.PivotTables.Count Next iWs CountPivotsInWorkbook = tmpCount End Function Call the function like this: Sub test() MsgBox CountPivotsInWorkbook(ActiveWorkbook) End Sub
{ "pile_set_name": "StackExchange" }
Q: Enable Emacs column selection using mouse How to use mouse to select column in Emacs? How to enable it? The emacs wiki RectangleMark says, there is mouse support for rectangle highlighting by dragging the mouse while holding down the shift key. The idea is that this behaves exactly like normal mouse dragging except that the region is treated as a rectangle. However, when I tried it, it doesn't work. No rectangle column is highlighted. I don't know if I need to use the next Lisp:rect-mark.el file or not, because when I look at it, it says, ;; If you use both transient-mark-mode and picture-mode, you will ;; probably realize how convenient it would be to be able to highlight ;; the region between point and mark as a rectangle. Have you ever ;; wished you could see where exactly those other two corners fell ;; before you operated on a rectangle? If so, then this program is ;; for you. To "see where exactly those other two corners fell"? Isn't that feature already provided out of box (ref http://www.gnu.org/software/emacs/manual/html_node/emacs/Rectangles.html)? I'm confused. UTSL tells me that it is duplicating what is already provided out of box by Emacs. Do I need the whole rect-mark.el file, or merely the mouse key-binding part only? UPDATE, for the record, for all my questions, I gather all the answers to here. A: Here is a solution: (defun mouse-start-rectangle (start-event) (interactive "e") (deactivate-mark) (mouse-set-point start-event) (rectangle-mark-mode +1) (let ((drag-event)) (track-mouse (while (progn (setq drag-event (read-event)) (mouse-movement-p drag-event)) (mouse-set-point drag-event))))) (global-set-key (kbd "S-<down-mouse-1>") #'mouse-start-rectangle) This works in Emacs 24.4 and later, when rectangle-mark-mode was introduced.
{ "pile_set_name": "StackExchange" }
Q: How to configure highlighting in Emacs diff mode? I use mercurial.el mode with Emacs. When I run vc-diff, I can see the diff, but, unlike the source code, it is not nicely highlighted: Reading such diffs is difficult. How do I configure Emacs, to highlight - and + lines with different colors? (red and blue, for example) to highlight word difference (like BitBucket and GitHub do) A: Try using M-x ediff-revision, which does an ediff instead of just a regular diff. That will give you word-differences and a side-by-side (or top/bottom) display. Check out the ediff manual. The Emacs wiki also has a number of modes for just regular diff files (like what you're looking at) - check it out. To just change the colors in the diff-mode which you're currently using, you can do something like: (defun update-diff-colors () "update the colors for diff faces" (set-face-attribute 'diff-added nil :foreground "white" :background "blue") (set-face-attribute 'diff-removed nil :foreground "white" :background "red3") (set-face-attribute 'diff-changed nil :foreground "white" :background "purple")) (eval-after-load "diff-mode" '(update-diff-colors))
{ "pile_set_name": "StackExchange" }
Q: How to display error messages in CodeIgniter In my controller I put this code to check if the shopping cart is empty: if (!$this->cart->contents()){ $this->session->set_flashdata('message', 'Your cart is empty!'); } $this->data['message'] = $this->session->flashdata('message'); $this->load->view('templates/header', $this->data); $this->load->view('bookings', $this->data); $this->load->view('templates/footer'); On my "bookings" view I set this code to display the message: <div id="infoMessage"><?php echo $message;?></div> But on the first page load the message "Your cart is empty!" is not showing. However, it will display when I press the F5 key or refresh the browser. I have already read the manual from codeigniter that says "CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared." However, I don't know where to set this message so it will be available on "next server requrest". A: There is no need to pass the data to the view and assign it as flashdata. The reason that it's not working the first time, is that flashdata is only available for the next server request. Loading the views isn't a server request. However, refreshing the page is. There are a couple of solutions to this: Pass the data directly and load the view. (Not using flash data.) Use flashdata and redirect to the page. Passing the data directly You could just pass it directly (personally I'd go with this option - I'm not sure why you'd want to use flashdata in this case, I would've thought that you'd always like to inform the user if their cart is empty...): Controller: if (!$this->cart->contents()) { $this->data['message'] = 'Your cart is empty!'; } $this->load->view('templates/header', $this->data); $this->load->view('bookings', $this->data); $this->load->view('templates/footer'); View: <div id="infoMessage"><?php echo $message;?></div> Using flashdata Or, if you want to use flashdata, then: Controller: if (!$this->cart->contents()) { $this->session->set_flashdata('message', 'Your cart is empty!'); } redirect('/your_page'); View: <div id="infoMessage"><?php echo $this->session->flashdata('message');?></div> If you want to use this method, you can't simply just load the view - due to the server request issue that I explained above - you have to redirect the user, using redirect('/your_page');, and the URL Helper $this->load->helper('url');. You can also send the appropriate HTTP header using the native PHP header function. Loading the view the first time won't work. You can use this $this->session->keep_flashdata('message'); to preserve the data for an additional request. I'd also check that your either auto-loading the session library or loading it in the constructor of your controller: $this->load->library('session'); (I'm fairly sure you will be, but it's worth checking anyway.) Finally, I know that some people who store session data in their database can have issues with flashdata, so that may be worth looking into, if none of the above helps. On a side note, personally I'd have a check to ensure that a variable is set before echoing it.
{ "pile_set_name": "StackExchange" }
Q: How are the SI units "generalised"? How exactly are the SI units generalised from their definitions? E.g. the kilogram is a weight of an object of cylindrical form, with diameter and height of about 39 mm, and is made of an alloy of 90 % platinum and 10 % iridium.. http://www.bipm.org/en/bipm/mass/ipk/ How do units such as these generalise to other materials, shapes and dimensions? How is it done? A: The definition of the kg is the mass of a particular lump of metal in Paris. The quote is trying (rather clumsily) to show that this isn't a very good definition because you can't make your own kg from any official definition. There is an almost complete project to replace the historical lump of metal with a new definition based on a physical effect that can be reproduced anywhere.
{ "pile_set_name": "StackExchange" }
Q: What is wrong with this getGeneratedKeys() JDBC statement? This code fragment PreparedStatement statement = connect.prepareStatement( query, Statement.RETURN_GENERATED_KEYS); statement.executeUpdate(query); try (ResultSet generatedKeys = statement.getGeneratedKeys()) { ... } keeps throwing java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement(). I'd say that generatedkeys ARE requested at creation of the statement, but apparently I'm wrong. What is the issue here? (I'm new to JDBC. What I'm trying to do is retrieving the primary key value which has been automatically set (AUTO_INCREMENTed) during the preceding record insertion. Maybe there is a better way to do that... I'm using mysql.) A: Your problem is this line: statement.executeUpdate(query); don't pass the query parameter in use the no parameter version: statement.executeUpdate(); The first version doesn't use the prepared statement you already made but instead makes a new one using your query String (without the RETURN_GENERATED_KEYS option)
{ "pile_set_name": "StackExchange" }
Q: Can crypto.SE help with implementing a secure protocol? Having lurked here for a while, I have a problem understanding how crypto.SE can help someone in the real world, other than academically. I've learnt a lot about aspects of cryptography and some of the ad hoc rules that seem to operate on this forum. But I don't see how what I've learnt can be put to non trivial practical use. Perhaps my issue is best illustrated with an example. Humpty Dumpty wants to securely talk to Pablo across the open internet, but doesn't want Candy to be able to listen in. Pablo also wants to know that the messages he's receiving do indeed come from Humpty Dumpy, and that Candy hasn't interfered with them. So I'm looking for some encryption and some authentication. Herein lies the problem. Rule 1 is than I mustn't implement my own cryptography. You're all familiar with this argument. This mantra is also applied to piecing together entire primitives, say a random IV generator of some design (or not - who knows), AES-CBC with some funky padding and a hash based MAC scheme. I then have to put all these primitives into some sort of secure order. There are a lot of variables and options to consider pertinent to my particular requirements. This is not a trivial attempt at just using MD5. Rule 2 is that I can't ask if I've assembled these code elements into some sort of secure order as implementation reviews are off topic. And it means that I certainly can't post code for review. This means that anything that I've produced might be total garbage and useless. The FAQ implies that if there's code it should be on the main Overflow forum. We know though that forum lacks the cryptographic experience to identify nuances in my implementation that might render it insecure. It chiefly focuses on syntax and execution flow. Rule 3. I then think best to use an off the shelf cryptographic library to get Humpty Dumpty talking to Pablo. Unfortunately I can't ask for a recommendation as that's off topic. So I'm left floundering around picking a library that has the nicest looking web site with no knowledge of whether it's any good cryptographically. (Rule 4.) This very question risks being closed as too broad thereby negating even any possibility of finding out how to successfully implement a protocol. This all leads to me wondering how crypto.SE can actually assist me in producing a working and secure protocol? It seems that I'm caught in a three or four way catch 22. A: Can crypto.SE help with implementing a secure protocol? Yes, but not when it comes to practical "software development". In it's simplest way, one could say Crypto.SE can help you understand what is going on and why, while other SE communities can help you with things like practical implementation and/or finding the tools or libraries you need. I'll dive into your four points (what you call "rules") to explain the details: Indeed, fact is Crypto.SE doesn't accept questions asking us to review a whole algo or scheme. So don't simply throw a paper (or alike lengthly algo/scheme/protocol description) at us, asking "is this secure?" as that's too broad and boils down to answerers having to write a small book. (To understand the issue with this, it may help to know people earn a living out there writing up such expanded analysis reports and/or papers.) But we do very well handle sub-analysis of individual building blocks. Quoting the related Meta Q&A which is also linked in our related "on hold" messages: However, you might like to break your problem down into specifics, such as "under these conditions, does structure X have desired security property Y?" which would be a perfect fit for us. This is also the reason (among other things) comments to questions frequently ask to clarify the exact scenario that is trying to be solved/handled. It is also correct to notice we don't do code reviews around here. The reason for that is that there is a dedicated community at SE that handles exactly what you're describing; it's called Code Review Stack Exchange. Users there do a pretty good job pointing out glitches and bugs in coding implementations, and even help optimizing your code in terms of security and performance. You can ask for recommendations at SE, just not at Crypto.SE. Quoting our help center If your question is looking for software and/or programming library recommendations, you should post it at Software Recommendations Fact is I frequently have to merge questions there. Last time I did so was around and about three days ago and — looking at the "thank you" messages I get — users are frequently pretty happy to learn that community exists, as it helps them find the software tools and libraries they're looking for. How to successfully implement a cryptographic algorithm or protocol depends on many things. Most of them were described by yourself… it assumes your algo, scheme, or protocol is secure. (You could also implement insecure things, but I'll skip diving into that as that isn't a frequent goal.) it assumes you know your way around in the coding language you're using. StackOverflow can help when it comes to learning that. Many of us also answer questions at StackOverflow. The beauty of SO is that it is known to be used by many experts in their individual fields; both cryptographic as well as non-cryptographic (eg Mark Adler, etc.) it assumes you don't introduce bugs in your code (which is where CodeReview.SE comes in). and sometimes it assumes you use the correct tools and/or libraries to achieve your goal. (see SoftwareRecommendations.SE). Long story short: what you're describing can't be handled by a single StackExchange community. But if you take a good look around, you'll notice there's an SE site for every part of your problem. By the way: your example Humpty Dumpty wants to securely talk to Pablo across the open internet, but doesn't want Candy to be able to listen in. Pablo also wants to know that the messages he's receiving do indeed come from Humpty Dumpy, and that Candy hasn't interfered with them. So I'm looking for some encryption and some authentication. would be on topic at our site. (Thinking about it, there's even a chance an alike question already exists.) It would also fit SoftwareRecommendations.SE if you reformulate it, asking for related programs and/or libraries that fit your target operating system(s). In the end, there are known and well-vetted solutions to your example problem and ready-to-use software solutions exist. This would practically void your need to create your own for your example. And in case some specific manual raises questions, SuperUser.SE tends to provide a very helping hand in explaining how to correctly use individual software (for example: OpenSSL, GPG/PGP, etc). So, there is no "Catch 22". Instead, what you're looking at is the huge truckload of hints to the fact that producing a working and secure protocol isn't a piece of cake as it takes a lot of knowledge in multiple areas and it also expects a lot of effort. If that weren't the case, everyone could do it… which would void the need for specialized programmers, experienced cryptographers, and — last but not least — cryptanalysts. The fact those jobs exist and aren't superfluous pretty much underlines the general problem that "creating your own" definitely ain't easy in the realms of cryptography. TL;DR As our help center explains, we're here to help you grasp the more theoretical side of all things related to cryptography, while other SE communities exist to help you implement and/or use that knowledge practically (as an example: crypto-related software development).
{ "pile_set_name": "StackExchange" }
Q: Spotify API get Related Artists Is there a way to get a list of related artists through the spotify api. Like the small list that displays in the actual program? Would be very useful if so, but I am not so sure Cheers A: Yes, it's available through libspotify. There's a SPArtistBrowse class that contains a lot of metadata, including the related artists. Check out the CocoaLibSpotify comes with a documentation package, where you can find more details on what's included: https://github.com/spotify/cocoalibspotify. Do note that it's currently extremely slow to load an entire SPArtistBrowse object. I'm assuming it's got something to do with libspotify loading it all in one chunk and on the main thread (?). From what I know, Spotify are suppose to remedy that in an upcoming version of libspotify, though. A: Get an artist's related artists is now available through the Spotify Web API. GET https://api.spotify.com/v1/artists/{id}/related-artists is the format. https://api.spotify.com/v1/artists/43ZHCT0cAZBISjO8DG9PnE/related-artists is an example request. For more information, see the API documentation. There is also a JSFiddle demo app.
{ "pile_set_name": "StackExchange" }
Q: S3 CORS Configuration: restricting to specific domains has no affect? I have a bucket on S3 with everything public, and the following CORS configuration: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>http://example.com</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> <CORSRule> <AllowedOrigin>http://localhost:3333</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> With that configuration, I would expect to only be able to get objects when requesting from http://example.com or http://localhost:3333, and receive 403s when linking to urls in that bucket from other domains. As it stands, I can still link to audio and image files in that bucket from http://dev.example.com as well as http://localhost:4444. What am I doing wrong? A: Setting the CORS configuration on a bucket isn’t on its own going to prevent anyone from being able to embed images or audio served from that bucket — and won’t otherwise cause any requests to the bucket to be denied. You can’t do that just through CORS configuration. Browsers are where all cross-origin restrictions are actually enforced, and browsers allow cross-origin URLs for audio and images to be embedded in any document, regardless of CORS settings. But by default browsers don’t allow frontend JavaScript code to access responses from cross-origin requests made with XHR or the Fetch or with Ajax methods from JavaScript libraries. That’s the only place where CORS comes in. It doesn’t affect behavior for normal cross-origin embedding of audio and images. Instead it allows you, from the server side, just to tell browsers which origins you want to unblock XHR/Fetch/Ajax requests from. And all that your bucket does differently when configured with CORS support is just to send the Access-Control-Allow-Origin response header and other CORS response headers. That’s it. All actual enforcement or relaxation of cross-origin restrictions is done by browsers on the client side — not on the server side by your bucket. In other words, as far as CORS configuration, what you set on your bucket is essentially just advisory information for browsers to use. So no matter what CORS configuration you make on the bucket, it still goes on accepting requests from all clients and origins it would otherwise; in other words, all clients from all origins still keep on getting responses from it just as they would otherwise. But browsers will only expose responses by your bucket to a cross-origin request from frontend JavaScript code running at a particular origin if your bucket is set to opt-in to permitting the request by responding with an Access-Control-Allow-Origin header that allows that origin. That’s the only effect you can cause with CORS configuration on the bucket. You can’t just through CORS configuration make it only allow the audio or image files it serves to be embedded just by particular origins. To do that, you need to use something other than just CORS configuration.
{ "pile_set_name": "StackExchange" }
Q: Add an image to object in Unity editor How do I add an image to an empty object? Which component should I add? I've tried adding an "Image" component but I can't figure out what to do afterwards. A: Drag the image you want into the project directory and this will create a sprite from that image. Then drag that image onto the empty gameobject and it will create a sprite renderer component and will automatically add the image as the sprite for the sprite renderer. You can also do this manually by adding the sprite renderer and selecting your image as the sprite for the sprite renderer. Note that if you are talking about Unity's UI system, simply do this... click "Add Canvas" tip, be sure to select "Scale with screen size" there. (In 99.99999% of cases, you want that option. It's bizarre Unity don't make it the default; just one of those whacky things about Unity.) simply click "Add Image" Add images like the crazy - it's that easy. You'll have to learn to use Unity's (superb) reactive layout system to position stuff on the screen in an advanced way. (Allow 3-4 months of study on that to become a hobbyist-level engineer on that system.) A: Create a raw image object using Create -> UI -> Raw Image. Then change the texture property as the png image.
{ "pile_set_name": "StackExchange" }
Q: Without alpha path how to decrease edge effect while paste icon I got a RGB332 LCD and a poor MCU to drive it . The MCU do not have a hardware accelerator nor do RGB332 display support an alpha path. So I used the color "black" as a "alpha color" to deal with icon paste work.Which means I fill the icon color data to background buffer while the data is not black. The problem I meet is that the icon showed it's own antialiased edge while the background is not black. And the "antialiased edge" just makes an edge effect from the background. Is there any way to deal with the situation ? A: The main problem is that I don't have "Layer" and "Alpha" to do the PS-like merge work. But the Icons are Pasted to a Frame buffer one by one. So my solution is : When each icon is being pasted,I could decide the front/background, which means I could detect the "antialiased edge" of the icons just like I have "layers". After I find the antialiased edges ,I filled the pixels with the middle color of the front/background. The LCD is RGB332,and the middle color calculation is just filling the edge with 75% background color + 25% front color. If the icon color is carefully designed, you don't even need a float calculation . The work maybe not that effective ,but really solved my problem.
{ "pile_set_name": "StackExchange" }
Q: Modifying struct instance using call to name in function parameter I am attempting to use Parse to call up some variables and put them into a struct that is already initialized. The calling of the variables is happening smoothly and the data is available, but the inputing of the class into the function is not happening. 'unit' is a struct that has the name, hp, attack, etc. variables contained within it. Is it not possible to pass along an instance of a struct and modify it's values like this? It would save me a lot of copy-pasting code to do it this way. Thanks for your help! func fetchStats(name: String, inout nameOfClass: unit) { var unitStatArray = [] let query = PFQuery(className: "UnitStats") query.whereKey("name", equalTo: name) query.findObjectsInBackgroundWithBlock{(objects:[PFObject]?, error: NSError?)->Void in if (error == nil && objects != nil){ unitStatArray = objects! } nameOfClass.name = "\(unitStatArray[0].objectForKey("name")!)" print("class name is \(nameOfClass.name)") print("cannon name is \(cannon.name)") nameOfClass.hitPoints = unitStatArray[0].objectForKey("hitPoints") as! Double nameOfClass.hitPointsMax = unitStatArray[0].objectForKey("hitPointsMax") as! Double nameOfClass.attack = unitStatArray[0].objectForKey("attack") as! Double nameOfClass.defense = unitStatArray[0].objectForKey("defense") as! Double nameOfClass.rangedAttack = unitStatArray[0].objectForKey("rangedAttack") as! Double nameOfClass.rangedDefense = unitStatArray[0].objectForKey("rangedDefense") as! Double nameOfClass.cost = unitStatArray[0].objectForKey("cost") as! Int } } fetchStats("3-inch Ordnance Rifle", nameOfClass: &cannon) A: This is an attempt to explain what I had in mind when writing my comment above. Because there's an asynchronous call to findObjectsInBackgroundWithBlock, the inout won't help you here. The idea is to add a callback fetched like this: func fetchStats(name: String, var nameOfClass: unit, fetched: unit -> ()) { // your code as above query.findObjectsInBackgroundWithBlock { // your code as above plus the following statement: fetched(nameOfClass) } } This can be called with fetchStats("3-inch Ordnance Rifle", nameOfClass: cannon) { newNameOfClass in nameOfClass = newNameOfClass } (all of this code has not been tested) The point is that you understand that your code is asynchronous (I know, I'm repeating myself). After you have called fetchStats you don't know when the callback (here: the assignment nameOfClass = newNameOfClass) will be executed. You cannot assume the assignment has been done after fetchStats has returned. So whatever you need to do with the changed nameOfClass: the corresponding statements must go into the callback: fetchStats("3-inch Ordnance Rifle", nameOfClass: cannon) { newNameOfClass in // do whatever you want with the received newNameOfClass } Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: winforms autocomplete format strings cities = result.Results.Entities.Cast<Address>().ToList(); foreach (Address address in cities) { int spaces = (30 - address.City.Length); string s1 = address.City.Trim(); for (int i = 0; i <= spaces; i++) { s1 += " "; } s1 += address.PostalCode; customCollection.Add(s1); } I want to concatenate two strings so that they are arranged in columns in a textbox autocompletecustomsource. No matter what I do I can't get the city and the postal code to align in columns. I want: New Bedlam 101010 New York 102010 I get: New Bedlam 101010 New York 102010 Tried a bunch of things, string.format, padright, nothing works. A: Just use string.Format with a left-justifying width specifier: foreach (Address address in cities) { string s1 = string.Format("{0,-30}{1}",address.City,address.PostalCode); customCollection.Add(s1); } Be aware that if your text box uses a variable-width font (like Arial) then the zip codes WON'T line up. Use a fixed-width font like Consolas or Courier New to align properly.
{ "pile_set_name": "StackExchange" }
Q: How to get high resolution images for Printers in .net? If you go to "Control Panel\Hardware and Sound\Devices and Printers" in Windows 7 (and i assume vista) you will see some nice pretty pictures of printers. See image below Is it possible to get access to these images through .net? For example to display them on a windows form? example http://windows7-guide.com/images/articles/devices-and-printers.jpg (source: maximumpc.com) A: They are available as .ICOs in %LOCALAPPDATA%\Microsoft\Device Metadata\dmrccache\ See http://www.istartedsomething.com/20090605/admiring-windows-7s-high-resolution-device-icons/
{ "pile_set_name": "StackExchange" }
Q: How to get mod_rewrite specific log messages in Windows Server and which file do I need to get? I have an issue on getting mod_rewrite specific log. I found this on a website and with help from a friend I managed to get this to run in Windows Server Powershell. Below is the command line: Get-content -Path D:/wamp64/xxx -wait -tail 10 | select-string -pattern "\[rewrite:" And my issue now is which file I need to get the content from to get the redirection logs? httpd.conf? .htaccess? Do I need to change anything else? I am sure that I need to point it to the correct path/file but I'm not sure which file to specified as it does not mention in here. I've also tried to create custom logs before but failed and causing the website to be down(which might be because of apache version? my apache is version 2.4.37) Please help me and TIA! Kindly drop a message here you need anything else. A: Manage to get rewrite logs by adding below for apache 2.4.37 in httpd-vhosts.conf: RewriteEngine On RewriteLog "d:/wamp64/logs/rewrite.log" LogLevel alert rewrite:trace8 Make sure to create a log with rewrite.log in folder logs so all the rewrite logs will go to that file.
{ "pile_set_name": "StackExchange" }
Q: How to save output of for loop in separate csv files? As an image and code that I attached below, I have a set of transaction data and each row has its industry name. reproducible example data: structure(list(Date = c(1201, 1201, 1201, 1201, 1201, 1201, 1201, 1201, 1201, 1201), Sex = c("Male", "Male", "Female", "Male", "Male", "Female", "Male", "Female", "Male", "Male"), Age = c(10, 15, 20, 15, 40, 50, 20, 30, 50, 20), City = c("Pheonix", "Atlanta", "Las Vegas", "Las Vegas", "Denver", "Pheonix", "Atlanta", "Las Vegas", "Las Vegas", "Minneapolis"), State = c("Arizona", "Georgia", "Nevada", "Nevada", "Colorado", "Arizona", "Georgia", "Nevada", "Nevada", "Minesota"), Industry = c("food", "furniture", "clothes", "transportation", "leisure", "food", "furniture", "food", "transportation", "furniture"), `no.of users` = c(48, 50, 83, 111, 186, 196.7, 230.4, 264.1, 297.8, 331.5), `no. of approval cases` = c(48, 21, 25, 48, 70, 63.7, 70.8, 77.9, 85, 92.1), `Total spending` = c(1541000, 512000, 1757000, 1117000, 1740500, 1634700, 1735100, 1835500, 1935900, 2036300)), .Names = c("Date", "Sex", "Age", "City", "State", "Industry", "no.of users", "no. of approval cases", "Total spending"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L)) What I would like to do is to subset only rows whose industry names match a condition and export it as separate csv files with the name of the file corresponding to its industry name. For example, let's say I have a list of current_industry<-c("food","furniture") First, I would like to subset rows whose industry names match "food" and then save it to csv files name 'food', then subsetting the following rows whose industry name matches to "furniture" and save it as separate csv files name 'furniture'. I wrote for-loop to do this, but this doesn't work as the following subsetting data replace the one beforehand. for(i in current_industry){ write.csv(subset(masterset, industry == i), "i.csv")} enter image description here A: I think this will work. After running this code, you will find food.csv and furniture.csv in your working directory. current_industry <- c("food", "furniture") for (i in current_industry){ dt2 <- subset(dt, Industry %in% i) write.csv(dt2, paste0(i, ".csv"), row.names = FALSE) } Update You may also consider the following. This code will save all industry as separated CSV file in your working directory. dt_list <- split(dt, f = dt$Industry) lapply(dt_list, function(dt){ write.csv(dt, paste0(unique(dt$Industry), ".csv"), row.names = FALSE) }) And the following will save only food and furniture. The key is to use current_industry to subset dt_list. dt_list <- split(dt, f = dt$Industry) dt_list2 <- dt_list[current_industry] lapply(dt_list2, function(dt){ write.csv(dt, paste0(unique(dt$Industry), ".csv"), row.names = FALSE) })
{ "pile_set_name": "StackExchange" }
Q: App Rejected - In App Purchase - Developer action needed My app got rejected because of In-App Purchase issues and the status of all of my In-App Purchase products is changed to Rejected. I googled the issue and did a little fake change in the Description of the In-App Products just to change the Status to "Waiting For Review". Now my question is Do I have to Wait for Apple Review team to review my In-App purchase and change the Status to "Ready to Submit"? or I can just Submit my Build again with In-App Purchase status "Waiting For Review" Also I read somewhere there I have to Select the In-App Purchase in my App Detail Page before submitting the Binary for Review. But I can't Find any thing like " In-App Purchase " in My App Details Page. Can you please, provide me step by step instruction on how can I resubmit my App with Proper In-App Purchase. A: See this link- iPhone : In-App Purchase(s) must be submitted with a new app version Before app submission you have to submit your all products.
{ "pile_set_name": "StackExchange" }
Q: side by side div with border above other border The current html of the website I work for is a mess, some because of the project itself (the pages are different from each other but have the same idea,like a newspaper) and some because the html team sux, lol. The idea is that I can have a row, or two columns without a border between then, two columns with a border, or a combination of these. I wrote the following css and html, it looks now organized, and you can use any of the combinations: CSS: /* start structure */ div#wrapper { margin: 0 auto; width: 1024px; } .group:after{ visibility: hidden; display: block; content: ""; clear: both; height: 0; } body { font-family: "Trebuchet MS"; } div#content { border: 1px solid #b2b2b2; } div.row { margin: 10px; } div.row.bb { margin-bottom: 0; padding-bottom: 10px; border-bottom: 1px solid #b2b2b2; } div.row.bt { margin-top: 0; padding-top: 10px; border-top: 1px solid #b2b2b2; } div.column { margin: 10px; float: left; } div.column.left { width: 660px; } div.column.right { width: 322px; } div.column.left.br { width: 659px; margin-right: 0; padding-right: 10px; border-right: 1px solid #b2b2b2; } /* end structure */ HTML: <div id="wrapper"> <div id="content"> <div class="row">a</div> <div class="row bt bb">b</div> <div class="columns group"> <div class="column left br"><p>c</p><p>c</p><p>c</p><p>c</p></div> <div class="column right">d</div> </div> <div class="row bt bb">a</div> <div class="columns group"> <div class="column left"><p>c</p><p>c</p><p>c</p><p>c</p></div> <div class="column right">d</div> </div> <div class="row bt">a</div> </div> </div> But I found a problem. When using two columns with border div.column.left.br, if the right column is taller than the left column, the border ends where the left column ends. I know I can solve it by putting the border both on the left and right columns, but I'm ending with a 2 pixel border. How can I solve it in my context? A: Add both a border-left on the right column and a border-right on the left column. Then move the right column to the left 1px. jsFiddle Example New CSS <style type="text/css"> /* start structure */ div#wrapper { margin: 0 auto; width: 1024px; } .group:after{ visibility: hidden; display: block; content: ""; clear: both; height: 0; } body { font-family: "Trebuchet MS"; } div#content { border: 1px solid #b2b2b2; } div.row { margin: 10px; } div.row.bb { margin-bottom: 0; padding-bottom: 10px; border-bottom: 1px solid #b2b2b2; } div.row.bt { margin-top: 0; padding-top: 10px; border-top: 1px solid #b2b2b2; } div.column { margin:10px 0; padding: 0 10px; float: left; } div.column.left { width: 660px; } div.column.right { width: 322px; } div.column.left.br + div.column.right { border-left: 1px solid #b2b2b2; margin-left:-1px; } div.column.left.br { width: 659px; margin-right: 0; padding-right: 10px; border-right: 1px solid #b2b2b2; } /* end structure */ </style>
{ "pile_set_name": "StackExchange" }
Q: Breeze getProperty "undefined is not a function" with 1.14.12 stack (EF6) I am receiving the following error: "undefined is not a function at updateRelatedEntityInCollection (localhost:3091/scripts/breeze.debug.js:14542:40" when using the breeze stack 1.14.12 with EF 6.1 / WebApi2. I have the following entities / maps defined server-side: public partial class Agency { public Agency() { this.Programs = new HashSet<AgencyProgram>(); this.Locations = new HashSet<Location>(); this.Participants = new HashSet<Participant>(); this.StaffMembers = new HashSet<Staff>(); } public int Id { get; set; } public string Name { get; set; } public virtual ICollection<AgencyProgram> Programs { get; set; } public virtual ICollection<Location> Locations { get; set; } public virtual ICollection<Participant> Participants { get; set; } public virtual ICollection<Staff> StaffMembers { get; set; } } public partial class Staff { public Staff() { this.CareerClubs = new HashSet<CareerClub>(); this.ClassFacilitation = new HashSet<ClassFacilitator>(); } public int AgencyId { get; set; } public int Id { get; set; } public string Name { get; set; } public virtual Agency Agency { get; set; } public virtual ICollection<CareerClub> CareerClubs { get; set; } public virtual ICollection<ClassFacilitator> ClassFacilitation { get; set; } } public class StaffMap : EntityTypeConfiguration<Staff> { public StaffMap() { // Primary Key this.HasKey(t => t.Id); // Properties this.Property(t => t.Name) .IsRequired() .HasMaxLength(50); // Table & Column Mappings this.ToTable("Staff"); this.Property(t => t.AgencyId).HasColumnName("AgencyId"); this.Property(t => t.Id).HasColumnName("Id"); this.Property(t => t.Name).HasColumnName("Name"); } } public class AgencyMap : EntityTypeConfiguration<Agency> { public AgencyMap() { // Primary Key this.HasKey(t => t.Id); // Properties this.Property(t => t.Name) .IsRequired() .HasMaxLength(50); // Table & Column Mappings this.ToTable("Agency"); this.Property(t => t.Id).HasColumnName("Id"); this.Property(t => t.Name).HasColumnName("Name"); } When I query the controller for Agencies (no filters, just a return context.Agencies I am getting back the following Json [{"$id":"1","$type":"System.Data.Entity.DynamicProxies.Agency_09777AD4C70881ED42DD78FB209FCD42C4995B1603097BBFD98C061405E71961, EntityFrameworkDynamicProxies-Model.Persistence","Locations":[],"Participants":[],"Programs":[],"StaffMembers":[{"$id":"2","$type":"System.Data.Entity.DynamicProxies.Staff_B3294F308AC9ED853C9E99FE2B1D765F9433E16FF56372757A43E397DECA38C7, EntityFrameworkDynamicProxies-Model.Persistence","Agency":{"$ref":"1"},"CareerClubs":[],"ClassFacilitation":[],"AgencyId":4,"Id":5,"Name":"Samuel Gonzalez"}],"Id":4,"Name":"Test Agency\r\n"}] Anytime Breeze 'types' the results (either with toType, or if I set metadata mappings) this error is thrown. The relatedEntity for the updateRelatedEntityInCollection is a populated Staff object without breeze props (no EntityAspect) and the inverseProperty associationName is Staff_Agency. I guess for whatever reason the Staff object is not getting 'breezified' after coming back from the server. A: The dynamic proxies are the problem. You'll need to turn them off, or use Breeze's EFContextProvider, which configures things correctly. Breeze recognizes the entities by the "$type" property, which becomes unrecognizable when proxies are used.
{ "pile_set_name": "StackExchange" }
Q: Apache2 has errors while starting after reinstalling SSL Certificate? I recently purchased and set up a VPS, and one of the first steps I took was to purchase and install an SSL Certificate. I had issues getting everything set up, but after quite a bit of research and head pounding it was finally set up correctly. I had a rewrite in the .htaccess file that forced https connections. Everything was sunshine and lolly-pops. Then came heartbleed! I had my SSL certificate reissued, and created new private keys. I then followed these steps to create a chained file. Now, when I try to start apache2, I'm getting the following error: [Mon Apr 28 10:32:59 2014] [warn] RSA server certificate CommonName (CN) `example.com' does NOT match server name!? [Mon Apr 28 10:32:59 2014] [error] Unable to configure RSA server private key [Mon Apr 28 10:32:59 2014] [error] SSL Library Error: 185073780 error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch What exactly does that mean? The certificate was just reissued, so there shouldn't have been any changes to the server name. Did I flub making the chain file? Other Information Ubuntu 12.04 LTS, with Apache 2.2.22. Oddness: I updated OpenSSL, and had no issues, prior to reissuing the cert. Now openssl version returns "OpenSSL 1.0.1 14 Mar 2012". Furthermore, I went to this checker and this checker after setting everything back up, and got a clean bill of health for both. However, I don't think I ever restarted apache after changing the certificates. Thoughts, advice, and guidance are appreciated! Update In my default-ssl I have it pointing to the following: SSLCertificateFile /etc/apache2/ssl/developingawesomeness.com.crt SSLCertificateKeyFile /etc/apache2/ssl/developingawesomeness.com.key SSLCertificateChainFile /etc/apache2/ssl/developingawesomeness.com.chain.pem Those files are in those directories as well. A: I'm not sure what the issue was exactly, but I created yet another csr and had my certificate re-reissued. Comodo actually sent different files than they had previously. Starting from scratch and chaining the necessary files fixed the issue.
{ "pile_set_name": "StackExchange" }
Q: image validation using image header in codeigniter to prevent hacking I want a method for validating image files. I have tried validating using image type and its formats and size. I need another validation with high accuracy. I am asking because my site has hacked by an uploaded image file containing code. The hacker has written code in .png format and uploaded it as an image in my site. From that moment he started hacking my site. Kindly help me to get a high validation for an image file using its header. I have validation like below: function upload() { //set preferences $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'txt|pdf'; $config['max_size'] = '100'; //load upload class library $this->load->library('upload', $config); if (!$this->upload->do_upload('filename')) { // case - failure $upload_error = array('error' => $this->upload->display_errors()); $this->load->view('upload_file_view', $upload_error); } else { // case - success $upload_data = $this->upload->data(); $data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>'; $this->load->view('upload_file_view', $data); } } A: You have allowed filetypes of txt and pdf. You should use $config['allowed_types'] = 'gif|jpg|png'; If it is images you are uploading.
{ "pile_set_name": "StackExchange" }
Q: Add effect when a div has been removed I want add effect to this "move up" of other div when I remove one. Here html: <ul id="fds"> <li> <h3>one</h3> <p>Hello guys</p> <p> <button class="remove">x</button> </p> </li> <li> <h3>two</h3> <p>Hello guys</p> <p> <button class="remove">x</button> </p> </li> <li> <h3>three</h3> <p>Hello guys</p> <p> <button class="remove">x</button> </p> </li> <li> <h3>four</h3> <p>Hello guys</p> <p> <button class="remove">x</button> </p> </li> </ul> Here JavaScript: $("#fds").delegate(".remove", 'click', function() { var $li = $(this).closest("li"); $li.fadeOut(300, function() { $li.remove(); }) }) Here a JS to test this. A: Set the top margin to minus the height to give a better UX. $("#fds").delegate(".remove", 'click', function() { var $li = $(this).closest("li"); $li.css({opacity: 0}).animate({marginTop: -1 * $li.height()}, 400, function() {$li.remove();}) }) li { border: 1px solid red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="fds"> <li> <h3>one</h3> <p>Hello guys</p> <p> <button class="remove">x</button> </p> </li> <li> <h3>two</h3> <p>Hello guys</p> <p> <button class="remove">x</button> </p> </li> <li> <h3>three</h3> <p>Hello guys</p> <p> <button class="remove">x</button> </p> </li> <li> <h3>four</h3> <p>Hello guys</p> <p> <button class="remove">x</button> </p> </li> </ul>
{ "pile_set_name": "StackExchange" }
Q: PHP ForEach Error Here is my code: <?php $query1 = 'SELECT * From Drink'; $GetName= mysql_query($query1);?> <?php foreach ($GetName as $GetNames) : ?> <?php echo $GetNames['Name']; ?> <?php endforeach; ?> The error I'm getting is this: Warning: Invalid argument supplied for foreach() in (removed for privacy) on line 16 I've looked at other questions similar to this one, and they don't quite answer the question. I'm not interested (currently) in finding a different way to go about doing this. I already have an alternate way, but I was taught this way and I'd like to know why it is failing. It isn't a problem with the database or the query, because this: <?php if ($GetName) { while($row = mysql_fetch_array($GetName)) { $name = $row["Name"]; echo "$name<br>"; } } Works just fine. Can anyone help me? A: So, I got it working. The problem was the way I connected to the database. Once I switch to PDO, as IOIO MAD implied, it worked just fine. Also Kudos to Itay Moav -Malimovka, because his suggestion did get rid of the error. Thanks for all of your help everyone, I'm glad I got this resolved.
{ "pile_set_name": "StackExchange" }
Q: Прописная буква при употреблении только части имени учреждения Добрый день. Имеется составное название учреждения, в котором только первое слово пишется с прописной буквы. Например, Высшая нормальная школа. Следует ли слово "школа" писать с прописной буквы, если оно используется без других слов? Например: Он учился в Высшей нормальной школе. Уже через несколько лет после окончания он вернулся в эту Школу в качестве преподавателя. Следует ли во втором предложении слово "школа" писать с прописной буквы? Спасибо. A: Школа должна писаться со строчной буквы. Написание прописной буквы в усеченных названиях возможно только в ЧАСТНЫХ случаях.Это касается следующих написаний: Государственный Литературный музей (Литературный музей), Государственный Исторический музей (Исторический музей), Государственный академический Большой театр (Большой театр), Государственная Третьяковская галерея (Третьяковская галерея). В этом случае два первых слова в составе имен собственных пишутся с прописной буквы, так как второе слово стоит в начале УСЕЧЕННОГО НАЗВАНИЯ и является БОЛЕЕ ИНФОРМАТИВНЫМ.
{ "pile_set_name": "StackExchange" }
Q: Reduce returns undefined I have an Array of Objects (Cars) : var car = [ {speed: 20, color: "red"}, {speed: 5, color: "blue"}, {speed: 80, color: "yellow"}, {speed: 79, name: "orange"} ]; and a function that should return the fastest Car in the Array : function getFastestCar(cars) { cars.reduce(function (prevFastestCar,curFastestcar) { if (curFastestcar.speed > prevFastestCar.speed) return curFastestcar; else return prevFastestCar; }, {speed: -Infinity, name: "test"}); }; After searching for a few hours I couldn´t find any solution why the function is returning undefined. I debugged the code and the function works perfectly fine, except in the last "step" it somehow replaces the fastest Car with undefined. I´m trying to understand the concept behind the reduce Method I know that there are easier ways to do this, but I´m curious why it is not working correctly. A: You need to return the reduced value from the function. return cars.reduce(..); See the description of reduce. Return value The value that results from the reduction.
{ "pile_set_name": "StackExchange" }
Q: What does this theorem statement mean? This is from Royden's Real Analysis book (4th edition). On page 17, Proposition 9 says: Every nonempty open set is the disjoint union of a countable collection of open intervals. At first, I thought it meant that: if $X$ is a non-empty open set then there is a set of intervals $I=\{I_1,I_2,I_3,..\}$ such that: (a) $X=\cup_j(I_j)$; (b) if $j \neq k$ then $I_j \cap I_k = \emptyset$. But from the proof, this doesn't seem right. So I looked up "disjoint union" (https://mathworld.wolfram.com/DisjointUnion.html) but it looks like it gives you back a set of tuple - so I'm not sure how to interpret this. A: Your understanding is correct. The definition of disjoint union in your link is perhaps a little misleading: it is best to see it as defining a binary operator DisjointUnion$(A,B)$ that takes two arbitrary sets as input, and outputs a set that consists of an image of $A$ and an image of $B$ under a simple mapping, such that these two images are disjoint. But when we say that a set $C$ is the disjoint union of $A$ and $B$, it usually means that (i) $C=A\cup B$ and (ii) $A\cap B=\emptyset$. Unfortunately this usage clashes with $C=$ DisjointUnion$(A,B)$ in the link.
{ "pile_set_name": "StackExchange" }
Q: How to GROUP multiple records from two different SQL statements I have a table called tbl which contains all the data I need. I have many columns in this table, but for purposes of this example I will only list the columns necessary to accomplish this task. Here's how data stored in the tbl (note uID is char(20) and cID is int)*: uID cID 1 10 1 11 1 12 2 11 We usually query this table like SELECT * FROM tbl WHERE uID = "1" So it returns uID cID 1 10 1 11 1 12 But I also need to return the row where uID is different but cID do match. Or grab the uID of the second row (which is 2) based on cID and do a select statement like this: SELECT * FROM tbl WHERE uID in ('1','2') That query will return what I'm looking for uID cID 1 10 1 11 1 12 2 11 This table contains a lot of rows and I want to be able to do this programatically for every call where cID matches and uID is different. Any suggestions? A: I think this may be what you want: SELECT * FROM tbl WHERE uID = '1' UNION ALL SELECT * FROM tbl WHERE uID <> '1' AND EXISTS (select 1 from tbl tbl2 where tbl2.uId = '1' and tbl2.cID = tbl.cID);
{ "pile_set_name": "StackExchange" }
Q: Plotting Pandas Multiindex Bar Chart How can I plot a Python Pandas multiindex dataframe as a bar chart with group labels? Do any of the plotting libraries directly support this? This SO post shows a custom solution using matplotlib, but is there direct support for it? As an example: quarter company Q1 Blue 100 Green 300 Q2 Blue 200 Green 350 Q3 Blue 300 Green 400 Q4 Blue 400 Green 450 Name: count, dtype: int64 ...can this dataframe be plotted with group labels like this? Thanks in advance, Rafi A: import pandas as pd data = pd.DataFrame([ ('Q1','Blue',100), ('Q1','Green',300), ('Q2','Blue',200), ('Q2','Green',350), ('Q3','Blue',300), ('Q3','Green',400), ('Q4','Blue',400), ('Q4','Green',450), ], columns=['quarter', 'company', 'value'] ) data = data.set_index(['quarter', 'company']).value data.unstack().plot(kind='bar', stacked=True) If you don't want to stack your bar chart: data.unstack().plot(kind='bar')
{ "pile_set_name": "StackExchange" }
Q: Unable to get numbers from window.location.search I am using the following code in my JS file: var match = window.location.search.match(/(\d*)/); this.room = (match) ? decodeURIComponent(match) : 0; And I am trying to just get the numbers from my URL. For example, in www.myurl.com/streams228, I just want to get the 228. The issue I am getting is it is just returning %2, nothing else, or 0. A: Try the following: var url ="www.myurl.com/streams228" var match = url.match(/([\d]+)/g); console.log(match[0]);
{ "pile_set_name": "StackExchange" }
Q: Using the same app.config for windows service and GUI I have have running windows service that is using it's app.config for getting some important values. Now I would like to provide a different GUI application that provide a way to change these important values and save it to the same app.config. My question is this: will it be possible to share this app.config between the projects by using "Add as a link" and if I then use my GUI application and change some values, will this be reflected in the windows service? EDIT: If this works, then perhaps someone also know the details of how the linking works in a more technical view? A: Both the projects can share the same app.config. Not sure about linking, but you can have same structure and values in two different config, but when deploying it, deploy it in same folder as windows service. Now regarding updating the values of app.config, they will not get reflected in windows service, if win service is running. You will need to restart the windows service for this. Because app settings are cached in memory, and loaded in memory when app starts. You can use ConfigurationManager.RefreshSection to refresh the loaded config in memory. You can read about it on MSDN. You will have have to do this in your windows service. Hope this info helps you.
{ "pile_set_name": "StackExchange" }
Q: Apache Camel: set an object dependency before operation with Spring In this example, I am trying to set the object dependency before calling businessLogic. I am receiving a nullpointer because that 'consumer' object is not set. Here is the basis of the example and mostly trying to use the Spring DSL. http://camel.apache.org/polling-consumer Section: Timer based polling consumer Here is my camel/spring config: <bean id="simpleOutboxMessageConsumer" class="org.berlin.camel.esb.logs.mq.SimplePrintMessageConsumer"/> <!-- Continue with spring dsl for ESB --> <camelContext id="myCamel" xmlns="http://camel.apache.org/schema/spring"> <!-- Define a MQ consumer template --> <consumerTemplate id="consumer" /> .... </camelContext> <route id="fromOutboxAndConsume"> <from uri="timer://foo?period=30000" /> <to uri="bean:simpleOutboxMessageConsumer?method=businessLogic" /> </route> Java code @Component public class SimplePrintMessageConsumer { private static final Logger logger = Logger.getLogger(SimplePrintMessageConsumer.class); private int count; @Autowired private ConsumerTemplate consumer; public void setConsumer(final ConsumerTemplate consumer) { this.consumer = consumer; } public void businessLogic() { logger.info("Launching business logic to consume outbox, blocking until we get a message >>>"); while (true) { // Consume the message final String msg = consumer.receiveBody("activemq:queue.outbox", 3000, String.class); logger.info("Printing message found from queue: " + msg); if (msg == null) { // no more messages in queue break; } } } } There is a nullpointer at the usage of the consume object. I am thinking that spring is not just autowiring that bean properly. Even if I didn't use spring, how would I pass the consumer template object to this bean? A: This should work <bean id="simpleOutboxMessageConsumer" class="....SimplePrintMessageConsumer"> <property name="consumer" ref="consumer"/> </bean> Remove the @AutoWire , I am checking on why the @Autowire is not working by the way
{ "pile_set_name": "StackExchange" }
Q: Geometry question mismatch with the book solution Question: A point $M$ moves on the curve $y^2 = 8x + 4$. A line $L$ passes through $M$ and is perpendicular to the line $x+3=0$, the foot of the perpendicular is $Q$. If $M$ is the midpoint of $PQ$, find the equation of the locus of $P$. What I did: Distance between the point $P$ and the line $L$ is: $\dfrac{Ax_p + By_p+C}{\sqrt{A^2+B^2}}$, where $A=1, B=0, C=3$ according to the equation of $L$, and the sign of $\sqrt{A^2+B^2}$ is the opposite of $C$, so it is negative. Finally, the distance between $L$ and $P$ is $-(x_P+3)$. Since the point $M$ is the midpoint of $PQ$, which is a horizontal line (obviously because it is perpendicular to the vertical line $x+3=0$), then the $x$-coordinate of $M$ would be $x_M = \dfrac{-(x_P+3)}{2}$. If now $x$-coordinate is replaced in the curve equation, we get that: ${y_M}^2 = - 8 \left( \dfrac{x_P+3}{2} \right) + 4 = -4x_P - 12 + 4 = 4(-x_P-2) $. But the solution in the book is $4(x_P-2)$. What am I doing wrong here? A: Try this $$ \frac{{x_P + x_Q }} {2} = x_M $$ thus $$ \frac{{x_P - 3}} {2} = x_M $$ Now $$ y^2 _M = 8x_M + 4 $$ and since $$y_M=y_P$$ you have $$ y^2 _P = 8\left( {\frac{{x_P - 3}} {2}} \right) + 4 $$ Therefore $$ y^2 _P = 4x_P - 8 = 4\left( {x_P - 2} \right) $$ Thus $$ y^2 _P = 4\left( {x_P - 2} \right) $$ As as in your book. It's clear now?
{ "pile_set_name": "StackExchange" }
Q: Check for each row in several columns and append for each row if the requirement is met or not. python I have the following example of my dataframe: df = pd.DataFrame({'first_date': ['01-07-2017', '01-07-2017', '01-08-2017'], 'end_date': ['01-08-2017', '01-08-2017', '15-08-2017'], 'second_date': ['01-09-2017', '01-08-2017', '15-07-2017'], 'cust_num': [1, 2, 1], 'Title': ['philips', 'samsung', 'philips']}) If the cus_num is equal in the column The Title is equal for both rows in the dataframe The second_date in a row <= end_date in an other row If all these requirements are met the value True should be appended to a new column in the original row. Because I'm working with a big dataset I'm looking for an efficient way to do this. In this case only the first record should get a true value. I have checked for the apply with lambda and groupby function in python but couldnt find a way to make these work. A: Try this (spontaneously I cannot come up with a faster method): import pandas as pd import numpy as np df["second_date"]=pd.to_datetime(df["second_date"], format='%d-%m-%Y') df["end_date"]=pd.to_datetime(df["end_date"], format='%d-%m-%Y') df["new col"] = False for cust in set(df["cust_num"]): indices = df.index[df["cust_num"] == cust].tolist() if len(indices) > 1: sub_df = df.loc[indices] for title in set(df.loc[indices]["Title"]): indices_title = sub_df.index[sub_df["Title"] == title] if len(indices_title) > 1: for i in indices_title: if sub_df.loc[indices_title]["second_date"][i] <= sub_df.loc[indices_title]["end_date"][i]: df["new col"] = True break df["new_col"] = new_col First you need to make all date columns comparable with eachother by casting them into datetime. Then create the additional column you want. Now create a set of all unique customer numbers and iterate through them. For each customer number get a list of all row indices with this customer number. If this list is longer than 1, then you have several same customer numbers. Then you create a sub df of your dataframe with all rows with the same customer number. Then iterate through the set of all titles. For each title check if there is the same title somewhere else in the sub df (len > 1). If this is the case, then iterate through all rows and write True in your additional column in the same row where the date condition is met for the first time.
{ "pile_set_name": "StackExchange" }
Q: php main file not seeing included file variable OK most the answers on S.O. are BACKWARDS from what I am having an issue with. My variable is not seen FROM the included file. I have never ran into this, and it is messing everything up. I was using smarty, but since it cant see the var, I went back to old fashion php templating, and still cannot see the var.. here is the scripts in question (a gaming site ofc). INCLUDED FILE: prep_feature_game.php foreach($games->gamexml->game as $game){ $d = parseDate($game['releasedate']); $game['date_month'] = $d['month']; $game['date_day'] = $d['day']; $game['date_year'] = $d['year']; $game['image_60x40'] = showImage($game['foldername'],'60x40'); $game['genrelist'] = displayGenreList($game['gameid']); //debugPrint($game);die(); $game_list[] = $game; } CONTROL PAGE: switch ($page) { default: include('includes/prep_feature_game.php'); // NOTE $GAME_LIST HAS THE ARRAY ^ display('feature_game'); break; AND THE DISPLAY FILE: FEATURE_GAME.PHP <h1><?=SITE_NAME;?>'s Featured Games!</h1> <table> <?PHP // TEST FOR $GAME_LIST foreach($game_list as $field=>$data){ echo $data['gamename']; } /* this produces the error: Notice: Undefined variable: game_list in C:\xampp\htdocs\ix2\themes\missingpiece\feature_game.php on line 7 */ }// end switch page I have many variations over the years of these templates, and the "included" files have never produced this kind of error. I know that included files act as though the script contained is inserted where the include is at. why is the receiving script unable to see the variable produced from the included script. These are all included, so it should not be an issue PS I noticed this started happening when I upgraded from php v5 - php v7, doubt it has anything to do with that, I havent checked that yet since include files are pretty standard. A: Your question is not showing the definition of the display function, but unless you declare $game_list as a global within that function it is out of scope. If you include the template it'll work. include('includes/prep_feature_game.php'); include('feature_game.php'); Or add parameters to your display function. display('feature_game', $game_list); Or if you're using smarty you must assign the variable first. $smarty->assign('game_list', $game_list); $smarty->display('feature_game.tpl');
{ "pile_set_name": "StackExchange" }
Q: Best practice to manage date and days I am working on a project where I have many operations to manage. Each operation have an end date and is composed by a certain amount of tasks. I want to display reminders (a text displayed on the screen) if a task is not done before [end date] - X days. All the data is stored in MySQL database and I work with PHP and HTML5. Which datatype is (are) the best to work with date and days (to perform calculations)? Can I work with Date() and subtract days in a easy way? I do not have a specific technical question, but I think sharing best way to proceed is a good thing, right? I'm curious to know what are the best ways to proceed and open to any proposal! A: I recommend to store your date in mysql at field timestamp because you can use default value CURRENT_TIMESTAMP - it very helpful, and i think you shouldn't worry about it, there is a plenty of functions:: mysql: select now(); +---------------------+ | now() | +---------------------+ | 2015-04-08 12:13:18 | +---------------------+ select now() - interval 1 day; +------------------------+ | now() - interval 1 day | +------------------------+ | 2015-04-07 12:13:29 | +------------------------+ select now() - interval 7 day; +------------------------+ | now() - interval 7 day | +------------------------+ | 2015-04-01 12:13:38 | +------------------------+ select now() - interval 1 month; +--------------------------+ | now() - interval 1 month | +--------------------------+ | 2015-03-08 12:13:58 | +--------------------------+ php: <?php var_export([ date('Y-m-d H:i:s', strtotime('now')), date('Y-m-d H:i:s', strtotime('- 1 day')), date('Y-m-d H:i:s', strtotime('- 7 day')), date('Y-m-d H:i:s', strtotime('- 1 month')), ]); /* Result: array ( 0 => '2015-04-08 15:15:42', 1 => '2015-04-07 15:15:42', 2 => '2015-04-01 15:15:42', 3 => '2015-03-08 15:15:42', ) */ And sometimes very helpful to create table like: CREATE TABLE t1 ( ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ); in result your field ts will be automatically seted and updated...
{ "pile_set_name": "StackExchange" }
Q: awk to Fill Empty Column value with Previous Non-Empty Column value: Would like to read the first column then Fill downward Empty Column value with Previous Non-Empty Column value. Input.txt 20 0 ABC 1 N DEFABC 0 CHARGE 1 ABC 1 N GHIABC 0 CHARGE 2 ABC 1 N JKLABC 0 CHARGE 3 ABC 1 N MNOABC 0 CHARGE 4 ABC 1 N PQRABC 0 CHARGE 210&&-2 0 ABC 1 N DEFABC 0 CHARGE 1 ABC 1 N GHIABC 0 CHARGE 2 ABC 1 N JKLABC 0 CHARGE 3 ABC 1 N MNOABC 0 CHARGE 4 ABC 1 N PQRABC 0 CHARGE 2130&&-4&-6&&-9 0 ABC 1 N DEFABC 0 CHARGE 1 ABC 1 N GHIABC 0 CHARGE 2 ABC 1 N JKLABC 0 CHARGE 3 ABC 1 N MNOABC 0 CHARGE 4 ABC 1 N PQRABC 0 CHARGE Have tried below command script and it is working fine if the file separted "," de-limiter and it is not working for FS="" and FS ="\t" for the above sample input. $ awk -f FillEmpty.awk Input.txt $ cat FillEmpty.awk BEGIN { FS = "" } $1 != "" { print } $1 == "" { # fill in blanks for (i = 1; i <= NR; i++) if ($i == "") $i = Saved[i] print } { # save all fields for (i = 1; i <= NR; i++) Saved[i] = $i } Desired Output: 20 0 ABC 1 N DEFABC 0 CHARGE 20 1 ABC 1 N GHIABC 0 CHARGE 20 2 ABC 1 N JKLABC 0 CHARGE 20 3 ABC 1 N MNOABC 0 CHARGE 20 4 ABC 1 N PQRABC 0 CHARGE 210&&-2 0 ABC 1 N DEFABC 0 CHARGE 210&&-2 1 ABC 1 N GHIABC 0 CHARGE 210&&-2 2 ABC 1 N JKLABC 0 CHARGE 210&&-2 3 ABC 1 N MNOABC 0 CHARGE 210&&-2 4 ABC 1 N PQRABC 0 CHARGE 2130&&-4&-6&&-9 0 ABC 1 N DEFABC 0 CHARGE 2130&&-4&-6&&-9 1 ABC 1 N GHIABC 0 CHARGE 2130&&-4&-6&&-9 2 ABC 1 N JKLABC 0 CHARGE 2130&&-4&-6&&-9 3 ABC 1 N MNOABC 0 CHARGE 2130&&-4&-6&&-9 4 ABC 1 N PQRABC 0 CHARGE Any suggestions ...! A: Awk way with formatting preserved awk '/^ /{$0=(x)substr($0,21)}{x=substr($0,0,20)}1' file And another way without needing the length of fields(very similar to tom feneches answer) awk '/^ /{$0=(x)substr($0,length(x)+1)}{x=$1}1' file Output of both 20 0 ABC 1 N DEFABC 0 CHARGE 20 1 ABC 1 N GHIABC 0 CHARGE 20 2 ABC 1 N JKLABC 0 CHARGE 20 3 ABC 1 N MNOABC 0 CHARGE 20 4 ABC 1 N PQRABC 0 CHARGE 210&&-2 0 ABC 1 N DEFABC 0 CHARGE 210&&-2 1 ABC 1 N GHIABC 0 CHARGE 210&&-2 2 ABC 1 N JKLABC 0 CHARGE 210&&-2 3 ABC 1 N MNOABC 0 CHARGE 210&&-2 4 ABC 1 N PQRABC 0 CHARGE 2130&&-4&-6&&-9 0 ABC 1 N DEFABC 0 CHARGE 2130&&-4&-6&&-9 1 ABC 1 N GHIABC 0 CHARGE 2130&&-4&-6&&-9 2 ABC 1 N JKLABC 0 CHARGE 2130&&-4&-6&&-9 3 ABC 1 N MNOABC 0 CHARGE 2130&&-4&-6&&-9 4 ABC 1 N PQRABC 0 CHARGE A: This works for fixed width: awk 'substr($0,0,24) ~ $1 { f=$1 }{ $0=f substr($0, length(f)+1) } 1' file If there is something in the first column, save the value to f. Either way, substitute the value into the line. The 1 at the end ensures that the line is printed. Testing it out: $ awk 'substr($0,0,24) ~ $1 { f=$1 }{ $0=f substr($0, length(f)+1) } 1' file 20 0 ABC 1 N DEFABC 0 CHARGE 20 1 ABC 1 N GHIABC 0 CHARGE 20 2 ABC 1 N JKLABC 0 CHARGE 20 3 ABC 1 N MNOABC 0 CHARGE 20 4 ABC 1 N PQRABC 0 CHARGE 210&&-2 0 ABC 1 N DEFABC 0 CHARGE 210&&-2 1 ABC 1 N GHIABC 0 CHARGE 210&&-2 2 ABC 1 N JKLABC 0 CHARGE 210&&-2 3 ABC 1 N MNOABC 0 CHARGE 210&&-2 4 ABC 1 N PQRABC 0 CHARGE 2130&&-4&-6&&-9 0 ABC 1 N DEFABC 0 CHARGE 2130&&-4&-6&&-9 1 ABC 1 N GHIABC 0 CHARGE 2130&&-4&-6&&-9 2 ABC 1 N JKLABC 0 CHARGE 2130&&-4&-6&&-9 3 ABC 1 N MNOABC 0 CHARGE 2130&&-4&-6&&-9 4 ABC 1 N PQRABC 0 CHARGE
{ "pile_set_name": "StackExchange" }
Q: Detect if page was redirected or loaded directly(Javascript) Currently, I want to display a label on the first page of my site a user visits. To make it simple, say I only care about page1.html and page2.html. Is it possible to check if the user was redirected from page1.html to page2.html?(Perhaps with cookies?) Edit: On page1.html, I set a cookie, which would expire in a minute. On page2.html, I checked for the cookie. Works great! A: You can use document.referrer. The value is an empty string if the user navigated to the page directly (not through a link). For example when user come to URL via bookmaked links click. User type the full URL in address bar. Reference https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer
{ "pile_set_name": "StackExchange" }
Q: c# attributes and generic--list I have such generic class of list: using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lab7 { public class MyListClass<T>: IEnumerable<T> { public delegate void MyDelegate(); public event MyDelegate AddEvent; public event MyDelegate RemEvent; List<T> list; public T this[int index] { get { return list[index]; } set { list[index] = value; } } public void Add(T item) { list.Add(item); if (AddEvent != null) AddEvent(); } public void Remove(T item) { list.Remove(item); if (RemEvent != null) RemEvent(); } public void RemoveAt(int index) { list.RemoveAt(index); if (RemEvent != null) RemEvent(); } public MyListClass() { list = new List<T>(); } public MyListClass(List<T> list) { this.list = list; } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return list.GetEnumerator(); } #region Events /*static void AddHandler() { Console.WriteLine("Объект добавлен в коллекцию"); } static void RemoveHandler() { Console.WriteLine("Объект удалён из коллекции коллекцию"); }*/ #endregion } } Where i must put attribute to write something to different classes, according to type of this list? How do I write this attribute? I didn't understand sense of attributes in this lab. If you want to see all lab, it's here Write generic class of list with opportunity to generate events when you call some class methods. Information about events must e written in some files, which must be determinated by attached to this class attribute. A: If I understand correctly, you are asked to write to a specified file information about the events fired when some specified methods are called. This file must be specified through a class level Attribute. I think (not easy to understand what you are asking) the Attribute should be defined in the generic type T. If thats what you are asking I would do something similar to the following: Define your custom attribute: [AttributeUsage(AttributeTargets.Class)] public class LogFileAttribute: Attribute { readonly string path; public LogFileAttribute(string path) { this.path = path; } public string Path { get { return this.path; } } } Modify your generic list class: public class MyListClass<T> : IEnumerable<T> { public delegate void MyDelegate(); public event MyDelegate AddEvent; public event MyDelegate RemEvent; private LogFileAttribute logFileAttribute; List<T> list; public T this[int index] { get { return list[index]; } set { list[index] = value; } } public void Add(T item) { list.Add(item); if (AddEvent != null) { AddEvent(); } if (this.logFileAttribute != null) { logEvent("Add"); } } public void Remove(T item) { list.Remove(item); if (RemEvent != null) { RemEvent(); } if (this.logFileAttribute != null) { logEvent("Remove"); } } public void RemoveAt(int index) { list.RemoveAt(index); if (RemEvent != null) { RemEvent(); } if (this.logFileAttribute != null) { logEvent("RemoveAt"); } } public MyListClass() { list = new List<T>(); checkLogFileAttribute(); } public MyListClass(List<T> list) { this.list = list; checkLogFileAttribute(); } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return list.GetEnumerator(); } private void logEvent(string methodName) { File.AppendAllLines(this.logFileAttribute.Path, new string[] { methodName + " called." }); } private void checkLogFileAttribute() { object[] attributes = typeof(T).GetCustomAttributes(typeof(LogFileAttribute), false); if (attributes.Length > 0) { this.logFileAttribute = (LogFileAttribute)attributes[0]; } } } Now if you define the following class: [LogFile(@"C:\EventLog.txt")] public class Foo { readonly int id; public Foo(int id) { this.id = id; } public int Id { get { return this.id; } } } And run the following code: MyListClass<Foo> foos = new MyListClass<Foo>(); foos.Add(new Foo(1)); foos.Add(new Foo(2)); you will get the desired behavior (if I understood your question correctly). EDIT: Removed Append form LogFileAttribute as it didn't make any sense in this context.
{ "pile_set_name": "StackExchange" }
Q: Ubuntu 16.04 won't upgrade I use Ubuntu 16.04 and want to upgrade. root@desktop:/# lsb_release -a LSB Version: core-9.20160110ubuntu0.2-amd64:core-9.20160110ubuntu0.2-noarch:security-9.20160110ubuntu0.2-amd64:security-9.20160110ubuntu0.2-noarch Distributor ID: Ubuntu Description: Ubuntu 16.04.4 LTS Release: 16.04 Codename: xenial root@desktop:/# apt-get update Hit:1 http://gb.archive.ubuntu.com/ubuntu xenial InRelease Get:2 http://security.ubuntu.com/ubuntu xenial-security InRelease [107 kB] Hit:3 http://ppa.launchpad.net/hda-me/higan/ubuntu xenial InRelease Get:4 http://gb.archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB] Get:5 http://gb.archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB] Hit:6 http://archive.canonical.com/ubuntu xenial InRelease Hit:7 http://archive.canonical.com xenial InRelease Fetched 323 kB in 0s (482 kB/s) Reading package lists... Done root@desktop:/# apt-get upgrade Reading package lists... Done Building dependency tree Reading state information... Done Calculating upgrade... Done 0 to upgrade, 0 to newly install, 0 to remove and 0 not to upgrade. root@desktop:/# apt-get dist-upgrade Reading package lists... Done Building dependency tree Reading state information... Done Calculating upgrade... Done 0 to upgrade, 0 to newly install, 0 to remove and 0 not to upgrade. root@desktop:/# do-release-upgrade Checking for a new Ubuntu release No new release found. It thinks that it doesn't need to upgrade. Earlier today I ran apt-get dist-upgrade and the output appeared to show that the upgrade worked. Here is /var/log/apt/history.log Start-Date: 2018-06-25 14:09:40 Commandline: apt-get dist-upgrade Requested-By: admin (1000) Install: libqpdf21:amd64 (8.0.2-3~16.04.1, automatic), intel-microcode:amd64 (3.20180425.1~ubuntu0.16.04.1, automatic), iucode-tool:amd64 (1.5.1-1ubuntu0.1, automatic), linux-headers-4.4.0-128:amd64 (4.4.0-128.154, automatic), linux-headers-4.4.0-128-generic:amd64 (4.4.0-128.154, automatic), libqmi-glib5:amd64 (1.16.2-1ubuntu0.16.04.1, automatic), amd64-microcode:amd64 (3.20180524.1~ubuntu0.16.04.1, automatic), libwebpdemux1:amd64 (0.4.4-1, automatic), libllvm5.0:amd64 (1:5.0-3~16.04.1, automatic), linux-image-4.4.0-128-generic:amd64 (4.4.0-128.154, automatic), linux-signed-image-4.4.0-128-generic:amd64 (4.4.0-128.154, automatic), linux-image-extra-4.4.0-128-generic:amd64 (4.4.0-128.154, automatic), libdrm-common:amd64 (2.4.83-1~16.04.1, automatic) Upgrade: perl-base:amd64 (5.22.1-9ubuntu0.3, 5.22.1-9ubuntu0.5), libqmi-proxy:amd64 (1.12.6-1, 1.16.2-1ubuntu0.16.04.1), libgcrypt20-dev:amd64 (1.6.5-2ubuntu0.4, 1.6.5-2ubuntu0.5), libimage-magick-perl:amd64 (8:6.8.9.9-7ubuntu5.9, 8:6.8.9.9-7ubuntu5.11), linux-headers-generic:amd64 (4.4.0.97.102, 4.4.0.128.134), libdrm-nouveau2:amd64 (2.4.76-1~ubuntu16.04.1, 2.4.83-1~16.04.1), linux-libc-dev:amd64 (4.4.0-127.153, 4.4.0-128.154), gnupg-agent:amd64 (2.1.11-6ubuntu2, 2.1.11-6ubuntu2.1), scdaemon:amd64 (2.1.11-6ubuntu2, 2.1.11-6ubuntu2.1), ruby2.3:amd64 (2.3.1-2~16.04.9, 2.3.1-2~16.04.10), libimage-magick-q16-perl:amd64 (8:6.8.9.9-7ubuntu5.9, 8:6.8.9.9-7ubuntu5.11), libegl1-mesa-dev:amd64 (17.0.7-0ubuntu0.16.04.2, 17.2.8-0ubuntu0~16.04.1), imagemagick:amd64 (8:6.8.9.9-7ubuntu5.9, 8:6.8.9.9-7ubuntu5.11), linux-image-generic:amd64 (4.4.0.97.102, 4.4.0.128.134), libmagickwand-6.q16-2:amd64 (8:6.8.9.9-7ubuntu5.9, 8:6.8.9.9-7ubuntu5.11), linux-signed-image-generic:amd64 (4.4.0.97.102, 4.4.0.128.134), perl-modules-5.22:amd64 (5.22.1-9ubuntu0.3, 5.22.1-9ubuntu0.5), console-setup-linux:amd64 (1.108ubuntu15.3, 1.108ubuntu15.4), libxatracker2:amd64 (17.0.7-0ubuntu0.16.04.2, 17.2.8-0ubuntu0~16.04.1), console-setup:amd64 (1.108ubuntu15.3, 1.108ubuntu15.4), flashplugin-installer:amd64 (29.0.0.171ubuntu0.16.04.1, 30.0.0.113ubuntu0.16.04.1), libegl1-mesa:amd64 (17.0.7-0ubuntu0.16.04.2, 17.2.8-0ubuntu0~16.04.1), libmagic1:amd64 (1:5.25-2ubuntu1, 1:5.25-2ubuntu1.1), libgcrypt11-dev:amd64 (1.5.4-3+really1.6.5-2ubuntu0.4, 1.5.4-3+really1.6.5-2ubuntu0.5), linux-signed-generic:amd64 (4.4.0.97.102, 4.4.0.128.134), perl-doc:amd64 (5.22.1-9ubuntu0.3, 5.22.1-9ubuntu0.5), libgbm1:amd64 (17.0.7-0ubuntu0.16.04.2, 17.2.8-0ubuntu0~16.04.1), dirmngr:amd64 (2.1.11-6ubuntu2, 2.1.11-6ubuntu2.1), libperl5.22:amd64 (5.22.1-9ubuntu0.3, 5.22.1-9ubuntu0.5), libdrm-amdgpu1:amd64 (2.4.76-1~ubuntu16.04.1, 2.4.83-1~16.04.1), cups-filters:amd64 (1.8.3-2ubuntu3.1, 1.8.3-2ubuntu3.4), imagemagick-6.q16:amd64 (8:6.8.9.9-7ubuntu5.9, 8:6.8.9.9-7ubuntu5.11), libmagickcore-6.q16-2-extra:amd64 (8:6.8.9.9-7ubuntu5.9, 8:6.8.9.9-7ubuntu5.11), libruby2.3:amd64 (2.3.1-2~16.04.9, 2.3.1-2~16.04.10), firefox-locale-en:amd64 (60.0.1+build2-0ubuntu0.16.04.1, 60.0.2+build1-0ubuntu0.16.04.1), libwayland-egl1-mesa:amd64 (17.0.7-0ubuntu0.16.04.2, 17.2.8-0ubuntu0~16.04.1), libgcrypt20:amd64 (1.6.5-2ubuntu0.4, 1.6.5-2ubuntu0.5), gpgv:amd64 (1.4.20-1ubuntu3.1, 1.4.20-1ubuntu3.2), libmm-glib0:amd64 (1.4.12-1ubuntu1, 1.6.4-1ubuntu0.16.04.1), libdrm2:amd64 (2.4.76-1~ubuntu16.04.1, 2.4.83-1~16.04.1), libwebkit2gtk-4.0-37:amd64 (2.18.5-0ubuntu0.16.04.1, 2.20.3-0ubuntu0.16.04.1), libgl1-mesa-dri:amd64 (17.0.7-0ubuntu0.16.04.2, 17.2.8-0ubuntu0~16.04.1), libmagickcore-6.q16-2:amd64 (8:6.8.9.9-7ubuntu5.9, 8:6.8.9.9-7ubuntu5.11), keyboard-configuration:amd64 (1.108ubuntu15.3, 1.108ubuntu15.4), libvirt0:amd64 (1.3.1-1ubuntu10.23, 1.3.1-1ubuntu10.24), qpdf:amd64 (6.0.0-2, 8.0.2-3~16.04.1), gnupg2:amd64 (2.1.11-6ubuntu2, 2.1.11-6ubuntu2.1), cups-filters-core-drivers:amd64 (1.8.3-2ubuntu3.1, 1.8.3-2ubuntu3.4), file:amd64 (1:5.25-2ubuntu1, 1:5.25-2ubuntu1.1), libdrm-intel1:amd64 (2.4.76-1~ubuntu16.04.1, 2.4.83-1~16.04.1), firefox:amd64 (60.0.1+build2-0ubuntu0.16.04.1, 60.0.2+build1-0ubuntu0.16.04.1), perl:amd64 (5.22.1-9ubuntu0.3, 5.22.1-9ubuntu0.5), modemmanager:amd64 (1.4.12-1ubuntu1, 1.6.4-1ubuntu0.16.04.1), imagemagick-common:amd64 (8:6.8.9.9-7ubuntu5.9, 8:6.8.9.9-7ubuntu5.11), libmagick++-6.q16-5v5:amd64 (8:6.8.9.9-7ubuntu5.9, 8:6.8.9.9-7ubuntu5.11), libdrm-radeon1:amd64 (2.4.76-1~ubuntu16.04.1, 2.4.83-1~16.04.1), mesa-vdpau-drivers:amd64 (17.0.7-0ubuntu0.16.04.2, 17.2.8-0ubuntu0~16.04.1), gnupg:amd64 (1.4.20-1ubuntu3.1, 1.4.20-1ubuntu3.2), desktop-file-utils:amd64 (0.22-1ubuntu5.1, 0.22-1ubuntu5.2), libjavascriptcoregtk-4.0-18:amd64 (2.18.5-0ubuntu0.16.04.1, 2.20.3-0ubuntu0.16.04.1), libdrm-dev:amd64 (2.4.76-1~ubuntu16.04.1, 2.4.83-1~16.04.1), linux-generic:amd64 (4.4.0.97.102, 4.4.0.128.134), wireless-regdb:amd64 (2015.07.20-1ubuntu1, 2018.05.09-0ubuntu1~16.04.1), libwebkit2gtk-4.0-37-gtk2:amd64 (2.18.5-0ubuntu0.16.04.1, 2.20.3-0ubuntu0.16.04.1), gpgsm:amd64 (2.1.11-6ubuntu2, 2.1.11-6ubuntu2.1) End-Date: 2018-06-25 14:12:54 Start-Date: 2018-06-25 14:16:01 Commandline: apt-get autoremove Requested-By: admin (1000) Remove: libqpdf17:amd64 (6.0.0-2), linux-headers-4.4.0-72-generic:amd64 (4.4.0-72.93), libllvm4.0:amd64 (1:4.0-1ubuntu1~16.04.2), linux-headers-4.4.0-72:amd64 (4.4.0-72.93), libgeoclue0:amd64 (0.12.99-4ubuntu1), linux-signed-image-4.4.0-72-generic:amd64 (4.4.0-72.93), linux-image-4.4.0-72-generic:amd64 (4.4.0-72.93), linux-image-extra-4.4.0-72-generic:amd64 (4.4.0-72.93) End-Date: 2018-06-25 14:16:24 I then rebooted and lsb_release -a shows I am still running 16.04. How do I upgrade? A: I bet if you run grep '^Prompt=' /etc/update-manager/release-upgrades, you'll see this: Prompt=lts This means that you want to upgrade to the next long-term support release. Even though Ubuntu 18.04 LTS was released almost two months ago (26 April 2018), do-release-upgrade doesn't see Ubuntu 18.04 LTS as the next LTS until about one month from now (26 July 2018), version 18.04.1. Why this is done is explained in "Why is “No new release found” when upgrading from a LTS to the next?" on Ask Ubuntu. How to Upgrade The easiest way to upgrade to Ubuntu 18.04 LTS anyway is to run this as root: do-release-upgrade -d You could alternatively edit Prompt= in /etc/update-manager/release-upgrades to read Prompt=normal And then run as root: do-release-upgrade Additional Resources Why is “No new release found” when upgrading from a LTS to the next? on Ask Ubuntu Upgrading LTS to LTS — why wait for the first point release? on Ask Ubuntu List of normal releases that Update Manager looks at List of LTS releases that Update Manager looks at
{ "pile_set_name": "StackExchange" }
Q: Input box with drop down items In Xamarin, how can I develop an input box that when the user inputs text, a dropdown list/menu appears with items that the user can click on? What type of input control do I need, and how do I code the dropdown list? Thanks in advance A: You have to put the combination of EditText and ListView to perform this. Refer this Link Android Hive for more details.
{ "pile_set_name": "StackExchange" }
Q: Need Help in Creating a Regular Expression for this Scenario I need to parse some information from lines of texts that follow a certain formatting layout. This is an example of how the text file would look: A. This is option a C. This is option c B. This is option b D. This is option d At the end of the day, all I want is that after parsing the above two lines, I would then have on my C# code: string OptionA = "This is option a"; string OptionB = "This is option b"; string OptionC = "This is option c"; string OptionD = "This is option d"; The space between A. and C. (or B. and D.) could either be a tab (\t) or a random number of white spaces. When stepping through the code and the line is read, this is how it looks: "A.\tThis is option a\tC. This is option c" Or it may look like this "A.\tThis is option a C. This is option c" I probably need some help splitting this line based on "\t" or a number of white spaces preceeding "C." as in the case of the above example. Any inputs would be greatly appreciated. A: The following regex should do it, @"^([A-Z])[.](.+[^\s])\s+([A-Z])[.](.+)$" Where for each line Groups[0] is the whole line Groups[1] is the first letter (e.g. A) Groups[2] is the first option (e.g. This is option a) Groups[3] is the second letter (e.g. C) Groups[4] is the second option(e.g. This is option c)
{ "pile_set_name": "StackExchange" }
Q: Need help on creating 4 relative layouts inside a grid layout (2x2) and put one button in the center of each relative layout I was trying to create a 2x2 grid layout with one relative layout inside each position in the grid. Later on, inside each position, I'd like to create a button and center it in the relative layout in which this button is inside (which in this case is the parent, am I right?) So, I was creating everything with no problem so far, but then I got stuck in centering the button. I've used android:gravity="center_horizontal" with android:layout_alignParentTop="true"; I've also tried using android:layout_gravity="center" None seem to be working. I'll post my full xml code below - trying to center the first button in the first relative layout, but no success. I've done some research and couldn't find an answer that suits my case. <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.victorpietro.musicproject.MainActivity"> <GridLayout android:id="@+id/gridLayout" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginBottom="8dp" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:rowCount="2" android:columnCount="2" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <RelativeLayout android:id="@+id/r_layout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="0" android:layout_columnWeight="1" android:layout_row="0" android:layout_rowWeight="1" android:gravity="fill"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_gravity="center" android:gravity="center_horizontal" android:text="Button" /> </RelativeLayout> <RelativeLayout android:id="@+id/r_layout2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_columnWeight="1" android:layout_row="0" android:layout_rowWeight="1" android:gravity="fill"> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </RelativeLayout> <RelativeLayout android:id="@+id/r_layout3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="0" android:layout_row="1" android:gravity="fill" android:layout_rowWeight="1" android:layout_columnWeight="1"> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </RelativeLayout> <RelativeLayout android:id="@+id/r_layout4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_row="1" android:gravity="fill" android:layout_rowWeight="1" android:layout_columnWeight="1"> <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </RelativeLayout> </GridLayout> </android.support.constraint.ConstraintLayout> A: remove android:gravity="fill" from RelativeLayout and add android:layout_gravity="center" <RelativeLayout android:id="@+id/r_layout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="0" android:layout_columnWeight="1" android:layout_row="0" android:layout_gravity="center" android:layout_rowWeight="1" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button"/> </RelativeLayout>
{ "pile_set_name": "StackExchange" }
Q: While sending json data in ajax gives an error like Unexpected token : I am creating login with facebook application in codeigniter. So, I want to pass json data into my controller using ajax. Here my code is like : var data = JSON.stringify(response); alert(data); $.ajax(function(){ type:"post", //contentType: 'application/json', //dataType: 'json', url:"<?php echo base_url().'login/insert_fb' ?>", data:{email:email,id:id} }).done(function(data){ alert(data); }); Here, In my login controller I have written code like this : function insert_fb() { $data = json_decode($this->input->post($response)); print_r($data); } Here, In data variable i got all json record.But when I call ajax function then it gives an error like Unexpected token :. So, how can I resolve this problem? Note : If I remove method and dataType and contentType then it gives an error like Unexpected token : at url. A: You have to remove function() from your ajax: var data = JSON.stringify(response); alert(data); $.ajax({ type:"post", //contentType: 'application/json', //dataType: 'json', url:"<?php echo base_url().'login/insert_fb' ?>", data:{email:email,id:id} }).done(function(data){ alert(data); });
{ "pile_set_name": "StackExchange" }
Q: MFC C++ in a Modeless Dialog Show a Modal one I have a modeless dialog. When I try and do a .DoModal() from there, it shows the dialog, but it still allows you to interact with the modeless dialog. This is how I create modeless dialog: MyMainEditorWindow = new CMyMain(this); MyMainEditorWindow->Create(CMyMain::IDD,GetDesktopWindow()); MyMainEditorWindow->ShowWindow(SW_SHOW); To do a modal one, from that modeless window, I do CMyDlg myDlg; int dialogbox = myDlg.DoModal(); Is there any way to do what I want? Where in modeless window, a dialog from it makes its window wait until it's decided. A: You need to set the parent window in the modal dialog's constructor. Docs for CDialog constructor say that if you set it to NULL, it uses main application window as the parent, and the default if unspecified is NULL.
{ "pile_set_name": "StackExchange" }
Q: How to catch event when an item in a BreadcrumbBar is clicked? I'm testing BreadcrumbBar from Vista Bridge Library. My very simple demo project is here (using latest version 1.4 at the moment). As we know, when clicking an item (on itself, not on the small breadcrumb on its tail), all the items on the right will disappear. I want to pop up a message box when that happens. How can I do it? A: I got a better alternative here from QuickZip.
{ "pile_set_name": "StackExchange" }
Q: How to read PowerShell .PSD1 files safely The PowerShell module manifest file format (.psd1) is essentially a Hashtable literal with certain keys expected. This is ideal for a configuration file for a PowerShell script. What I ultimately want to do is read a .psd1 file that contains a set of keys specific to the script. For example (MyScriptConfig.psd1): @{ FTPHost = "ftp.blah.com" FTPUserName = "blah" FTPPassword = "blah" } There's no reason I can't use XML, INI, JSON or whatever for this information, but I'd rather it use the same basic data format as PowerShell's module manifests. Obviously the easiest thing would be to read the text and pass it to Invoke-Expression which would return a Hashtable, but then it would invoke anything that's in the file, which is error prone and potentially unsafe. I thought I recalled a cmdlet for reading this data using a "safe" subset of PowerShell cmdlets, but I was thinking of ConvertFrom-StringData and DATA sections, neither of which let me read an arbitrary file containing a Hashtable literal. Is there something built into PowerShell that lets me do this? If there's nothing built in, then I would probably go the route of JSON or Key=Value with ConvertFrom-StringData. A: Powershell version 5 added the Cmdlet Import-PowershellDataFile for safely parsing PSD1 files. Prior to version 5, there were at least three solutions: The Cmdlet Import-LocalizedData. Which, though intended for processing language files, will read any PSD1 formatted file. # Create a test PSD1 file @' @{ a1 = 'a1' a2 = 2 a3 = @{ b1 = 'b1' } } '@ | Set-Content -Path .path\example.psd1 # Read the file Import-LocalizedData -BaseDirectory .\path -FileName example.psd1 -BindingVariable Data # Use the data $Data.a1 $Data.a3.b1 It is also possible to process in-line data with a Data Section (in-line sort of defeats the purpose). # Safely parse data $Data2 = DATA { @{ a1 = 'a1' a2 = 2 a3 = @{ b1 = 'b1' } } } # Use the data $Data2.a1 $Data2.a3.b1 The third being the PowerShell DSC parameter transformation attribute mentioned by @Jakub Berezanski. A: PowerShell DSC defines a parameter transformation attribute, used to support passing a path to a .psd1 file as the value of the ConfigurationData parameter when invoking a Configuration. This attribute is public and can be used in a custom function, such as: function Parse-Psd1 { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [Microsoft.PowerShell.DesiredStateConfiguration.ArgumentToConfigurationDataTransformation()] [hashtable] $data ) return $data } Parse-Psd1 C:\MyData.psd1 The attribute implementation calls an internal helper that evaluates the contents of the file in a restricted language context, where only the following cmdlets are permitted: Import-LocalizedData ConvertFrom-StringData Write-Host Out-Host Join-Path
{ "pile_set_name": "StackExchange" }
Q: .htaccess "deny from all" doesn't work correctly I`m trying to configure the .htaccess to deny downloads of a certificate file(.pfx). My website structure is: /app /resources - cert1.pfx .htaccess cert2.pfx My htaccess : <Files *.pfx> deny from all </files> In the directory explorer I don't see any of the certificate files. But when I try to download the following: localhost/resources/cert1.pfx The certificate file is downloaded... If I try to download certificate located in the root folder: localhost/cert2.pfx It throw a 403 forbidden error. I don't understand why one of the certificates is denied and the other one no. Any sense? Thanks. A: The reason you have one cert downloaded but second not is about Files. Simple *.pfx matches only files in that directory. Documentation says the following To address files found in a particular part of the filesystem, the <Files> and <Directory> sections can be combined. For example, the following configuration will deny access to /var/web/dir1/private.html, /var/web/dir1/subdir2/private.html, /var/web/dir1/subdir3/private.html, and any other instance of private.html found under the /var/web/dir1/ directory. <Directory "/var/web/dir1"> <Files "private.html"> Require all denied </Files> </Directory> Some other hints can be found here This setup is referring to .conf files, but in .htaccess you may use Location instead. Some more explanation. Also, I strongly recommend to use "Require" instead of outdated "Allow/Deny".
{ "pile_set_name": "StackExchange" }
Q: What is the intuition for semi-continuous functions? Here is the definition of semi-continuous functions that I know. Let $X$ be a topological space and let $f$ be a function from $X$ into $R$. (1) $f$ is lower semi-continuous if $\forall \alpha\in R$, the set $\{x\in X : f(x) > \alpha \}$ is open in X. (2) $f$ is upper semi-continuous if $\forall \alpha\in R$, the set $\{x\in X : f(x) < \alpha \}$ is open in X. I heard that semi-continuity is a generalization of one-sided continuity from left or right (as in single variable calculus) to continuity from "below" or "above", but I could not see from the definitions above how that is so. How can I see this intuitively? A: A function is continuous if the preimage of every open set is an open set. (This is the definition in topology and is the "right" definition in some sense.) The definitions you cite of semicontinuities claim that the preimages of certain open sets are open, but does not say so about all open sets. Note that $\{ \{f \in \mathbb{R} \mid f > \alpha\} \mid \alpha \in \mathbb{R} \} \cup \{ \{f \in \mathbb{R} \mid f < \beta\} \mid \beta \in \mathbb{R} \} $ is a (topological) basis for $\mathbb{R}$. (Finite intersections of such sets generate all the intervals $(a,b) \subset \mathbb{R}$, which is also a basis, although perhaps more recognizably so.) Consequently, a function that is both upper and lower semicontinuous has the property that the preimages of intervals are the intersections of two open preimages (an upper preimage and a lower preimage), so are open. Thus, being both upper and lower semicontinuous means being continuous. (Some minor details are elided in this argument, but are not essential.) As @Martín-BlasPérezPinilla observes, this has nothing to do with continuity from the right or left. If you wish to discuss those ideas, you should look up cadlag and caglad. One way to intuit upper and lower semicontinuity is to imagine dipping the graph of the function in paint. If you dip it so that the lower parts of the function are wetted, then you get the parts where $f(x) < \alpha$ where $\alpha$ is the level up to which you dipped the function. If you dip it so that only the upper parts of the function are wetted (perhaps by standing on your head), then you get the parts where $f(x) > \alpha$. To be upper semicontinuous, the definition you cite requires that all possible lower wetted subsets of the graph of the function project onto open subsets of the domain. This can be difficult if a connected component of the graph descends (to the right) to a closed endpoint that is below the function to the right of it -- dipping such a function in the paint only enough to include a (half-) neighborhood of the closed endpoint will end up with a little painted segment that may be open on one end and closed on the end of the closed endpoint. Such a function would not be upper semicontinuous. (Note that if the values of the function to the right were below (or at the same height as) the closed endpoint, then they would necessarily be painted any time the endpoint is, so the described scenario need not turn out the same.) A: "... semi-continuity is a generalization of one-sided continuity from left or right..." Utterly false. In lateral continuity the "side condition" is on the domain while in semicontinuity the "side condition" is on the range. The idea of continuity is "if $x$ is near of $c$ then $f(x)$ is near of $f(c)$". Semicontinuity relaxes the condition to "$f(x)$ is near of $f(c)$ or in this side of $f(c)$". See Semicontinuity in the Wikipedia.
{ "pile_set_name": "StackExchange" }
Q: Save Image To Phone? WP7 C# I'm trying to make an app with images that you can save to your phone. I don't even know where to begin. What is the simplest way to do this in C#? A: This article explains on how you can save a newly taken photo to the Pictures Hub. And this one is about saving to the IsolatedStorage. This should get you started! If you still have completely no idea what this is all about (since you say you're are an amateur), I suggest you read a couple of articles on Windows Phone 7 development first. On the App Hub are lots of articles and tutorials with code samples on dozens of topics to get started with Windows Phone 7 development. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: formatting issue when having decimal numbers as file names so basically I'm trying to generate a list of file names. What I have done so far is the following: total = Table[StringTemplate["/home/Projekt/output/b12_t`t`_a`a`.csv"]@<| "t" -> 0.01 k, "a" -> 0.01 l|>, {k, 1, 21}, {l, 0, 50}] Then I realized that, the mantissa ended with 0s are not displayed in full decimal place. For example: instead of showing /home/Projekt/output/b12_t0.01_a0.00.csv it shows /home/Project/output/b12_t0.01_a0.csv I know that normally we can use Precision[x] to print the exact number but in this case is does no help. Much appreciated if someone can give me a hint. A: Table[ StringTemplate[ "`t`", InsertionFunction -> (ToString@NumberForm[#, {1, 2}] &) ]@<|"t" -> 0.01 k|>, {k, 0, 10} ] {"0.00", "0.01", "0.02", "0.03", "0.04", "0.05", "0.06", "0.07", "0.08", "0.09", "0.10"}
{ "pile_set_name": "StackExchange" }
Q: script Table as Create via SSMS doesn't show unique index Using SQL Server Management Studio 2008, why can't I see unique index ( not primary key ) when I generate Create Table SQL code? It includes only primary key constraint. Is it by design ? There is a possibility to get SQL code for index creation via right mouse click on an index and "Script index as", but it is another step. A: Is the "Script Unique Keys" option set to TRUE in your SSMS? In SSMS, Tools -> Options will get you to the pop-up window shown below. A: Note that in SSMS 2012, you have to set "Script indexes" to TRUE to script out unique indexes.
{ "pile_set_name": "StackExchange" }
Q: Are the first solo flights by a student pilot more dangerous? The first solo flight is a nail-biting moment, not only for the student pilot, but also for the flight instructor who's sending him off. In theory not having a CFI reduces the margin of safety compared to flights with an instructor (at the same point in a student's training). I've also heard stories about mistakes and even crashes on first solo flights, and according to "Crashes of instructional flights" by Baker, Lamb, Li, and Dodd, solo flights account for about half of instructional flight crashes. Yet even though the biggest safety measure- a CFI- is gone, are these student solo flights really more dangerous? Are there any studies on accident rate among low time GA pilots vs (solo) students? Also, are incidents more common in the first solo flights than at other parts of a student's pilot training? A: There is no evidence to back the claim that the first solo ride of the student is more dangerous compared to the later ones. US NIH conducted a study on the accidents with solo pilots, which doesn't indicate that first-time solo fliers are any more prone to accident than others. Aircraft accidents with student pilots flying solo: analysis of 390 cases by Sjir Uitdewilligen and Alexander Johan de Voogt analyzed NTSB probable cause reports of 390 crashes that occurred in the period 2001 – 2005, concluding that, Student pilots flying solo show fewer injuries and fatalities compared to general instructional flights while in our sample first-time solo student pilots did not feature any fatalities. Note that this gives only the injuries and not the times the students got into accidents per se. Out of a total of 3811 accidents involving student pilots, 390 occurred while they were flying solo and around 50 involved first-time student solo pilots. Actually, student pilots themselves are prone to less accidents compared to others. From Comparative Analysis of Accident and Non-Accident Pilots by David C. Ison: Most accidents (49.1%) were conducted with individuals holding a private pilot certificate. Second in incidence were commercial pilots (28.2%), followed by Airline Transport Pilots (ATPs) (13.7%), and student pilots (5.7%) Considering that 20% of pilots hold a student certificate, these individuals have a disproportionally low accident occurrence. The report also gives some additional insight into the reason the first-time solo fliers have lesser injuries: ... first-time solo pilots are commonly confined to the airport and practice their takeoff and landings. Such operations may result in accidents, but they will occur near to the ground with a lower risk of a fatality The report also gives some data about higher experienced student pilots sustaining more injuries, though nothing conclusive, noting that, ... in 25 cases, student pilots were reported to have more than 100 and up to 322 h of flight experience. In the dataset, these pilots were significantly more often injured than students with less hours of flight experience. It has to be noted that as the hours logged gets more, the students get into more demanding flights which may be reason for this increase in injuries. A: I couldn't find any analysis of first solo flights, but based on NTSB accident reports it looks like accidents are very rare. There are only 60 reports of fatal part 91 (GA) accidents with the words "first solo" in the report, and 492 non-fatal accidents. But many of those are false positives anyway, because they include reports with things like "with his first solo occurring about a month prior to the accident", so the real numbers are lower. Training flights in general are very safe compared to other flights. In 2015, student pilots accounted for only 6.5% of non-commercial fixed-wing GA accidents. That's much lower than private (47.1%), commercial (26.6%) and even ATP (12.2%) certificate holders. AOPA has a detailed report called Accidents During Flight Instruction that comments on student solo flight in general, but not on first solos specifically. It says: Two-thirds of all fixed-wing training accidents come during primary instruction, and two-thirds of those are during the relatively few hours of solo flight by student pilots. However, fatalities on student solos are extremely rare. And it does give some information about your question on first solos vs. other phases of instruction: Two-thirds of all fatal fixed-wing accidents occurred during advanced instruction, less than half of them while pursuing a specific certificate, rating, or endorsement. Transition training, flight reviews, generic refresher training, and specialized instruction in areas such as mountain flying, aerobatics, and cropdusting collectively accounted for over 60 percent of all advanced dual accidents, including more than half the fatal accidents. Other people have already commented on why student solo flights in general are relatively safe: the student is primed with plenty of recent training and instructor feedback, and the flight conditions are well controlled. A: No. Anytime you get on a car or airplane or any mode of transportation, it is dangerous. Yet most of those journeys end without any incident. First solo is a very short flight, mostly of a few circuits of the traffic pattern. The instructor is watching and talking to the student. The student is well trained at that point and literally know what they are doing. I think Simon's comment is very important and needs to be remembered, most accidents can happen when confidence and ego can outweigh wisdom and learning. You should also notice that most of student's flying occur in VMC or better conditions. This includes both first solos and checkrides. Being the pilot in command, you can cancel the flight if you think any condition is not suitable.
{ "pile_set_name": "StackExchange" }
Q: Use Opus Audio instead of Vorbis in Java Minecraft Resource Packs Can I use the Opus CODEC instead of Vorbis for replacement OGG files in a Java Minecraft resource pack? A: No.                              
{ "pile_set_name": "StackExchange" }
Q: How to match keys in a dictionary with the elements in a list and store those key values to another dictionary in python? I have a dictionary like this: {'and': {'in': 0.12241083209661485, 'of': 0.6520996477975429, 'to': 0.7091938791256235}, 'in': {'and': 0.12241083209661485, 'of': -0.46306801953487436, 'to': -0.0654517869126785}, 'of': {'and': 0.6520996477975429, 'in': -0.46306801953487436, 'to': 0.8975056783377765}, 'to': {'and': 0.7091938791256235, 'in': -0.0654517869126785, 'of': 0.8975056783377765}} and a list like this: list1 = ['the', 'of', 'Starbcks', 'in', 'share', 'for', '%', 'fiscal', '2007', 'growth', 'year', 'cents', 'earnings', 'a', 'company', '2,400', 'net', 'abot', 'range', 'stores', 'revene', 'sales', 'gidance', '``', "''", 'earnings', 'provides', 'wew', 'net'] I want to traverse through the list and check whichever words equals the keys in the list, and then add those key values into another dictionary. Like from this example, I want this as my result: new_dict = {'in': {'and': 0.12241083209661485, 'of': -0.46306801953487436, 'to': -0.0654517869126785}, 'of': {'and': 0.6520996477975429, 'in': -0.46306801953487436, 'to': 0.8975056783377765}} I am doing something like this: for elem in l: temp_dict = dict((key,value) for key,value in similarity_matrix.iteritems() if key == elem) print temp_dict But I getting {} as my result. What's wrong and how to fix it? EDIT: Now, I took this: OrderedDict(for k in list1: if k in d: new_d[k] = d[k] else: new_d[k] = 0) i.e., the keys that are not there, will get values 0 in new_d. But, is there any way to get the dictionary in the same order as there were words in list1? Like the output should be: new_d : {'the' : 0, 'of': {'and': 0.6520996477975429, 'in': -0.46306801953487436,'to': 0.8975056783377765}, 'Starbucks' : 0, ......} A: list1 = ['the', 'of', 'Starbcks', 'in', 'share', 'for', '%', 'fiscal', '2007', 'growth', 'year', 'cents', 'earnings', 'a', 'company', '2,400', 'net', 'abot', 'range', 'stores', 'revene', 'sales', 'gidance', '``', "''", 'earnings', 'provides', 'wew', 'net'] d={'and': {'of': 0.6520996477975429, 'in': 0.12241083209661485, 'to': 0.7091938791256235}, 'of': {'and': 0.6520996477975429, 'to': 0.8975056783377765, 'in': -0.46306801953487436}, 'in': {'and': 0.12241083209661485, 'of': -0.46306801953487436, 'to': -0.0654517869126785}, 'to': {'and': 0.7091938791256235, 'of': 0.8975056783377765, 'in': -0.0654517869126785}} new_d ={} for k in list1: if k in d: new_d[k] = d[k] print(new_d) {'of': {'and': 0.6520996477975429, 'to': 0.8975056783377765, 'in': -0.46306801953487436}, 'in': {'and': 0.12241083209661485, 'of': -0.46306801953487436, 'to': -0.0654517869126785}} Or a dict comprehension: new_d ={ k: d[k] for k in list1 if k in d} checking if a key is in a dict or a set is O(1) Using your own code you could do the following which checks if the key is in your list: temp_dict = dict((key,value) for key,value in d.iteritems() if key in set(list1)) To keep the order the items were added you need to use collections.OrderedDict: from collections import OrderedDict new_d = OrderedDict(((k,d[k]) if k in d else (k,0) for k in list1 ))
{ "pile_set_name": "StackExchange" }
Q: json (only) - fully dynamic- jquery select box dropdown Hi I have a regular select box with values in it. The problem is it is so long it's causing page load speed issues especially over mobile networks and causing the page to fail on load more often than you might expect.. Since this field is rarely changed I thought it would be better as an event I googled this a lot and found very little about fully dynamic select box - so this is what I came up with HTML <br> <div class="ui-widget-header">Customer:</div> <select name="customer_id" id="customer_id" class="ui-widget-content" style="width:642px;"> <option value="1">Francis L. Mcbride</option> </select> jQuery <script> $(function() { $("#customer_id").click(function(){ $('#customer_id').prop("disabled", true); $.getJSON("select.php?table=customer", function(j){ var current = $("#customer_id").val(); var options = ''; $.map(j.params, function(item) { options += '<option value="' + item.id + ((current==item.id)?' selected':'')+'">' + item.name + '</option>'; }); $("#customer_id").html(options); $('#customer_id').prop("disabled", false); }); }); }); </script> hopefully you can see what I am doing - showing the "old" value in the drop down - then populating it and redrawing it from .getJSON call - the problem is that is doesn't work - - first click it shows only 1 item (top of the json get) then 2nd and subsequent clicks it flickers and changes the selected to the top of the list every time A: I fixed the latter part of it there was a typo around the select $.map(j.params, function(item) { options += '<option value="' + item.id + '"' +((current==item.id)?' selected':'')+'>' + item.name + '</option>'; }); IN CHROME: but it still fails to work on first use after page load.. very bizarre.. it appears that the browser animation literally finishes too fast after the first render of one option I feel confident that this is the case because if I simply use alerts around the getJSON call it renders fine first time (albeit with the alertbox interruption). IN FIREFOX totally different bug - brower refuses to not redraw new text into the selectbox. basically if you click the drop down it removes the previous setting ===================================================================== VERDICT There is no solution for this because you can't interrupt the drop-down event **at all**, so I decided upon a hybrid (poor) solution. Pseudo code solution: mask the selectbox with a event overlay containing a disabled input box only cause the overlay to swap to a dropdown underlay only after the user engages the event jQuery <script> $(function() { $("#customer_id_SlideButton").button({ icons: { primary: "ui-icon-triangle-1-s" }, text: false }); $('#customer_id_SlideDiv').hide(); $("#customer_id_SlideButton").click(function(e){ if ($('#customer_id_Overlay').is(":visible")){ $.getJSON("select.php?table=customer", function(j){ var current = $("#customer_id").val(); var options = ''; $.map(j.params, function(item) { options += '<option value="' + item.id + '"'+((current==item.id)?' selected':'')+'>' + item.name + '</option>'; }); $('#customer_id').html(options); $('#customer_id_SlideDiv').show(); $('#customer_id_Overlay').hide(); }); } else{ $('#customer_id_SlideDiv').hide(); $('#customer_id_Overlay').show(); } return false; }); $("#customer_id").change(function(){ $('#customer_id_FakeDisplay').val($("#customer_id option:selected").text()); }); }); </script> HTML <button id="customer_id_SlideButton" class="formbox" style=" z-index : 3; width:26px; height:26px; position:relative; top:29px; left: 200px;">customer_id Display</button><br> <div id="customer_id_Overlay" style="position: relative; top: -9px; height:21px; "> <input class="ui-widget-content formview" id="customer_id_FakeDisplay" disabled value="Russell Y. Guerrero" style="width:602px;"> </div> <div id="customer_id_SlideDiv" style="position: relative; top: -10px; height:21px; "d> <select name="customer_id" id="customer_id" class="ui-widget-content formbox" style="width:610px;"> <option value="2">Russell Y. Guerrero</option> </select> </div> Json {"params":[{"id":"7","name":"Amena D. Bradford"},{"id":"9","name":"Cameron N. Morse"},{"id":"8","name":"Camille E. Preston"},{"id":"10","name":"Doris Z. Cline"},{"id":"1","name":"Francis L. Mcbride"},{"id":"4","name":"Quamar Q. Gregory"},{"id":"5","name":"Reece W. Rhodes"},{"id":"2","name":"Russell Y. Guerrero"},{"id":"3","name":"Tamekah I. Barton"},{"id":"6","name":"Yetta V. Poole"}],"count":"10"} I don't like it but it fulfils all the objectives for me: only loads a single <option></option> unless needs changing - a very very rare event means I don't cause a server burden every time the page is loaded goes to get JSON for the select with no "pre-select" load hit (event driven server get) cleanly shows the change choices to the user NOTE thanks to PSL for his help he deleted his help thread for some reason FIDDLE you can see a jsfiddle of it (some of the positioning of the button looked bad so I reworked widthe and things but it works) http://jsfiddle.net/Ups54/
{ "pile_set_name": "StackExchange" }
Q: Display Next row after completing selection of all dropdowns in the all above rows My requirement is to display a row if all drop downs in the above row's value is not "Select Answer".If Any drop down's answer is "Select Answer" all the drop downs in the below row of its row should be hidden. How can i achieve that. Any idea. Below is my HTML code.. <table> <tr> <td> <select id="S1" class="dropdown"> <option value="" selected="selected">Select answer</option> <option value="1" >A</option> <option value="2">B</option> <option value="3">C</option> </select> </td> <td> <select id="S2" class="dropdown"> <option value="" selected="selected">Select answer</option> <option value="1">A</option> <option value="2" >B</option> <option value="3">C</option> </select> </td> </tr> <tr> <td> <select id="S2" class="dropdown"> <option value="" selected="selected">Select answer</option> <option value="1">A</option> <option value="2" >B</option> <option value="3">C</option> </select> </td> <td> <select id="S2" class="dropdown"> <option value="" selected="selected">Select answer</option> <option value="1">A</option> <option value="2" >B</option> <option value="3">C</option> </select> </td> </tr> </table> A: I created a jsFiddle that has working code in it. I would suggest modifying it to use more semantic markup, and you will have to add some logic to check up the stack (top most tr) to make sure to only show the ones that need to be shown, but this should get you a very good starting point to answering your problem.
{ "pile_set_name": "StackExchange" }
Q: temporary key binding in emacs I am not particularly satisfied how the viper mode works in Emacs. I am trying to write my own viper mode. I do not have any good programming experience in Elisp except for the number of customizations I have done using the .emacs file. I would like to know if I can change the key-bindings in Emacs temporarily and return them back to their original state as and when needed. A: Well if I understand your question correctly one easy way to do this would be to create your own minor mode (in addition to your own specific mode I'd say), made only of your temporary key-bindings. You give a name to that mode and then toggling all your temporary key-bindings on or off becomes as simple as calling your command: M-x salsabear-minor-mode You probably want to read scottfrazer's 45+ upvotes answer here on SO: Globally override key binding in Emacs where he explains how to create your own minor-mode containing your key-bindings.
{ "pile_set_name": "StackExchange" }
Q: mathML is not rendering at all I have written this math equation using MathML. I have tried both using .html and .xhtml. None of them fulfilled my desire. In html format it shows x y x y and in .xhtml format it shows the code. So how would I make it work? <!DOCTYPE html> <html lang="en"> <head> <title></title> </head> <body> <math display="inline" xmlns="http://www.w3.org/1998/Math/MathML" mode="display"> <mfrac> <mi>x</mi> <mi>y</mi> </mfrac> </math> <math display="block" xmlns="http://www.w3.org/1998/Math/MathML" mode="inline"> <mfrac> <mi>x</mi> <mi>y</mi> </mfrac> </math> </body> </html> A: Importing a javascript from mathjax solved my problem: <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> complite code looks like this: <!DOCTYPE html> <html> <head> <title>MathJax MathML Test Page</title> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> </head> <body> <math display="inline" xmlns="http://www.w3.org/1998/Math/MathML" mode="display"> <mfrac> <mi>x</mi> <mi>y</mi> </mfrac> </math> <math display="block" xmlns="http://www.w3.org/1998/Math/MathML" mode="inline"> <mfrac> <mi>x</mi> <mi>y</mi> </mfrac> </math> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Can quadcopters save energy by flying in formation? If two or more quadcopters are aligned, would the effect of drag due to the lead quadcopter's slipstream lead to measurable energy savings? And if so, how would one determine the optimal distance between the quadcopters? My thought are that some energy savings are possible, but that there must be some distance between the quadcopters to avoid the high pressure air behind the lead quadcopter interfering with the quadcopter that's behind. How great this distance is depends on the tilt of the lead quadcopter. Since the drag force is proportional with the square of the velocity this means that energy savings should be larger at high velocity, but unfortunately the tilt of the quadcopters will also be higher causing the minimal distance needed between the quadcopters to increase. A: Yes, drag can be reduced by formation flying. Geese using a low drag "V" formation. The authors of a 2001 Nature article stated that pelicans that fly alone beat their wings more frequently and have higher heart rates than those that fly in formation. It follows that birds that fly in formation glide more often and reduce energy expenditure (Weimerskirch, 2001). Any flying object (plane, bird, helicopter, etc) that creates a down-wash to create lift must also produce an opposite and equal up-wash. A trailing aircraft positioned properly can ride this "wave". Research aircraft flying a test point (low drag) for the Autonomous Formation Flight project over California's Mojave Desert. From the NASA Dryden Flight Research Center Web site. The goal of the Autonomous Formation Flight project was to demonstrate 10 percent fuel savings of the trailing aircraft. The project extended the symbiotic relationship of migrating formations of birds. In December 2001, an F/A-18 flying in the wingtip vortex behind another F/A-18 exhibited a 14-percent fuel savings. The project ended in late 2001
{ "pile_set_name": "StackExchange" }
Q: excel function "search of the decision function in R I have the question, whether it is possible in R to implement an excel function "search of the decision"? Is there function in R or it is necessary to create a script in R. It is necessary to solve the following equation by combining the X values to get 1,126 as the result. 1.126 = X / (X + 0.2) * (EXP (X + 0.2) -1) A: You can find the solution to this equation using uniroot. The solution to your equation is the same as the solution to X / (X + 0.2) * (exp(X + 0.2) -1) - 1.126 = 0 So ... Dec = function(X) X / (X + 0.2) * (exp(X + 0.2) - 1) - 1.126 uniroot(Dec, c(0,2)) (part of) the result is $root [1] 0.6959234 $f.root [1] -1.585758e-06 If you need more accuracy, you can adjust the tol parameter. uniroot(Dec, c(0,2), tol= 0.0000001) $root [1] 0.6959241 $f.root [1] 7.61391e-13
{ "pile_set_name": "StackExchange" }
Q: JavaScript - Sort array by two integer properties I have the following array of objects: const items = [ { name: "Different Item", amount: 100, matches: 2 }, { name: "Different Item", amount: 100, matches: 2 }, { name: "An Item", amount: 100, matches: 1 }, { name: "Different Item", amount: 30, matches: 2 } ] I need to sort these by matches and amount, so the final result looks like this: [ { name: "Different Item", amount: 100, matches: 2 }, { name: "Different Item", amount: 100, matches: 2 }, { name: "Different Item", amount: 30, matches: 2 }, { name: "An Item", amount: 100, matches: 1 } ] The first priority is to sort everything by matches, and then within those, I need to sort them by amount. I know I can sort by just matches or just amount like so: items.sort((a, b) => a.matches - b.matches); But how can I sort by both? A: You can use Array#sort. Objects will get sorted based firstly on matches then on amount. const items = [ { name: "Different Item", amount: 90, matches: 2 }, { name: "Different Item", amount: 100, matches: 1 }, { name: "An Item", amount: 80, matches: 1 }, { name: "Different Item", amount: 30, matches: 2 }, { name: "Different Item", amount: 40, matches: 1 }, { name: "Different Item", amount: 50, matches: 1 }, { name: "An Item", amount: 10, matches: 1 }, { name: "Different Item", amount: 20, matches: 2 }, ]; const r = [...items].sort((a, b) => b.matches - a.matches || b.amount - a.amount); console.log(r);
{ "pile_set_name": "StackExchange" }
Q: MediaRecorder video capturing in portrait mode I'm try to make custom video app. Iwork using settings in manifest 2.2 only (API 8). All goes well but I don't understand why portrait mode video does not differ from lanscape one. To make detection of device changed orientation I use this code within surfaceChanged() if (mCamera != null) { Camera.Parameters p = mCamera.getParameters(); try { mCamera.stopPreview(); } catch (Exception e) { // TODO: handle exception } int previewWidth = 0; int previewHeight = 0; if (mPreviewSize != null) { Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int rotation = display.getRotation(); switch (rotation) { case Surface.ROTATION_0: previewWidth = mPreviewSize.height; previewHeight = mPreviewSize.width; mCamera.setDisplayOrientation(90); break; case Surface.ROTATION_90: previewWidth = mPreviewSize.width; previewHeight = mPreviewSize.height; mCamera.setDisplayOrientation(0); break; case Surface.ROTATION_180: previewWidth = mPreviewSize.height; previewHeight = mPreviewSize.width; mCamera.setDisplayOrientation(270); break; case Surface.ROTATION_270: previewWidth = mPreviewSize.width; previewHeight = mPreviewSize.height; mCamera.setDisplayOrientation(180); break; } p.setPreviewSize(previewWidth, previewHeight); mCamera.setParameters(p); } try { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e) { Log.d(TAG, "Cannot start preview.", e); } } Works like a charm. If I rotate device surface change orientation, calling surfaceChanged, where camera is set to appropriate DisplayRotation. The question is how to determine later if the video captured either in lanscape mode or in portrait one. As I got all the videos are captured in landscape orientation. It does not depend of setDisplayOrientation which affect only preview process. Also exploring the problem I noticed that if to use standard Camera app it writes special tag to video file (seen in MediaInfo): Rotation : 90 for the portrait captured videos. But MediaRecorder class does not. Seems that is the problem. Anybody got to solve this? A: Found it ! Indeed, you can change the preview, you can tag the video, but there's no way to actually change the video... (maybe a speed issue or something) camera.setDisplayOrientation(90); To rotate the preview, then recorder.setOrientationHint(90); To tag the video as having a 90° rotation, then the phone will automatically rotate it when reading. So all you have to do is camera = Camera.open(); //Set preview with a 90° ortientation camera.setDisplayOrientation(90); camera.unlock(); holder = getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); recorder = new MediaRecorder(); recorder.setCamera(camera); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP); recorder.setOutputFile(getVideoFolder()+rnd.nextString()+".mp4"); recorder.setPreviewDisplay(holder.getSurface()); //Tags the video with a 90° angle in order to tell the phone how to display it recorder.setOrientationHint(90); if (recorder != null) { try { recorder.prepare(); } catch (IllegalStateException e) { Log.e("IllegalStateException", e.toString()); } catch (IOException e) { Log.e("IOException", e.toString()); } } recorder.start(); Hope it helps ;-) A: camera.setDisplayOrientation(90) does not work in all devices. Following solution work perfectly in different devices and also handling marshmallow runtime permission. See setCameraRotation method public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mHolder; private Camera mCamera; public static int rotate; private Context mContext; public CameraPreview(Context context, Camera camera) { super(context); mCamera = camera; mHolder = getHolder(); mHolder.addCallback(this); // deprecated setting, but required on Android versions prior to 3.0 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mContext = context; } public void surfaceCreated(SurfaceHolder holder) { try { // create the surface and start camera preview if (mCamera != null) { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } } catch (IOException e) { Log.d(VIEW_LOG_TAG, "Error setting camera preview: " + e.getMessage()); } } public void refreshCamera(Camera camera) { if (mHolder.getSurface() == null) { // preview surface does not exist return; } // stop preview before making changes stopPreview(); // set preview size and make any resize, rotate or // reformatting changes here setCamera(camera); // start preview with new settings startPreview(); } public void stopPreview(){ try { if(mCamera != null) mCamera.stopPreview(); } catch (Exception e) { // ignore: tried to stop a non-existent preview e.printStackTrace(); } } public void startPreview(){ try { if(mCamera != null) { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); }else{ Log.d(VIEW_LOG_TAG, "Error starting camera preview: " ); } } catch (Exception e) { Log.d(VIEW_LOG_TAG, "Error starting camera preview: " + e.getMessage()); } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. refreshCamera(mCamera); } public void setCamera(Camera camera) { //method to set a camera instance mCamera = camera; /** * add camera orientation and display rotation according to screen landscape or portrait */ setCameraRotation(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub if(mCamera != null){ mCamera.release(); } } public void setCameraRotation() { try { Camera.CameraInfo camInfo = new Camera.CameraInfo(); if (VideoCaptureActivity.cameraId == 0) Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, camInfo); else Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_FRONT, camInfo); int cameraRotationOffset = camInfo.orientation; // ... Camera.Parameters parameters = mCamera.getParameters(); int rotation = ((Activity)mContext).getWindowManager().getDefaultDisplay().getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; // Natural orientation case Surface.ROTATION_90: degrees = 90; break; // Landscape left case Surface.ROTATION_180: degrees = 180; break;// Upside down case Surface.ROTATION_270: degrees = 270; break;// Landscape right } int displayRotation; if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { displayRotation = (cameraRotationOffset + degrees) % 360; displayRotation = (360 - displayRotation) % 360; // compensate // the // mirror } else { // back-facing displayRotation = (cameraRotationOffset - degrees + 360) % 360; } mCamera.setDisplayOrientation(displayRotation); if (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { rotate = (360 + cameraRotationOffset + degrees) % 360; } else { rotate = (360 + cameraRotationOffset - degrees) % 360; } parameters.set("orientation", "portrait"); parameters.setRotation(rotate); mCamera.setParameters(parameters); } catch (Exception e) { } } } Now prepare media recorder with correct rotation so that recorded video play in right orientation. mediaRecorder.setOrientationHint(CameraPreview.rotate); private boolean prepareMediaRecorder() { mediaRecorder = new MediaRecorder(); mCamera.unlock(); mediaRecorder.setCamera(mCamera); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mediaRecorder.setOrientationHint(CameraPreview.rotate); mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW)); mediaRecorder.setOutputFile(filePath); mediaRecorder.setMaxDuration(15000); // Set max duration 15 sec. mediaRecorder.setMaxFileSize(10000000); // Set max file size 1M try { mediaRecorder.prepare(); } catch (IllegalStateException e) { releaseMediaRecorder(); return false; } catch (IOException e) { releaseMediaRecorder(); return false; } return true; } You can download complete sample https://github.com/umesh-kushwaha/Android_Video_Recording_portrait
{ "pile_set_name": "StackExchange" }
Q: Where did the mandatory "Feature-request" tag come from? Why am I forced to use the "feature-request" tag when I am not requesting a feature? This notification showed up for me today when editing an existing question, and when creating this new question. Is there any way to avoid it, other than entering this usually-incorrect tag? Meta is for meta-discussion, not just feature-requests, correct? [except, for this question, it IS a feature request. hrm.] A: The required tags were updated to include "bug discussion support feature-request"
{ "pile_set_name": "StackExchange" }
Q: Can ESP32 radiation cause health hazards? I am using ESP32 chips for a smart health monitoring device. I will use WiFi 802.11n or Bluetooth BLE/EDR depending on the amount of data to be transferred, so the unit will be mounted on hand, maybe another place of the body. It can be: upper back middle lower back middle front upper- chest wrist arm below the shoulder I could not find any resources for health risks of ESP32 radiation. Is there any possibility of getting cancer or any other health issues due to Bluetooth or WiFi radiation of the ESP32? A: Normal RF communications protocols all use non-ionizing radiation, which does not have any serious health concerns. In the worst case, it can heat your body up slightly (like a microwave oven, but at an incredibly low power level compared to the oven. If these were dangerous, we'd all be getting horribly maimed by our phones and laptops. With that said, because water absorbs 2.4GHz (and thus causes the aforementioned heating), you aren't going to get good signal out if you plan on implanting such a device. Chart from https://en.wikipedia.org/wiki/Non-ionizing_radiation:
{ "pile_set_name": "StackExchange" }
Q: What is the Japanese phrase to convey the meaning of "to declare attendance"? We as employees of a relatively big company are often prompted to log on to and log out from by wiping our fingers on a bio-metric scanner, for example, to declare our attendance. Shortly speaking, what is the Japanese word or phrase to convey the meaning of "to declare attendance"? In other words, what is the word or phrase to fill the following blank space? 社員は平日にバイオメトリックスキャナで _____ (し)なくてはならない。 The employees must declare their attendance on weekdays using a bio-metric scanner. Edit: Another example, 太郎:寝坊してしまいまして、すみません。 Taro: I am sorry for coming late. 店長:悪いですね。じゃあ、早く ____ して、このネギを切ってください。 Store manager: It is bad, isn't it? Well, please quickly "declare your attendance" and cut this onion. A: The phrases you are looking for would be: 「[出勤]{しゅっきん}・[退勤]{たいきん}の[打刻]{だこく}をする」 「出勤・退勤(の)[時刻]{じこく}を[記録]{きろく}する」 You could use 「[出社]{しゅっしゃ}・[退社]{たいしゃ}」 instead of 「出勤・退勤」 as well. EDIT: For your second example sentence, you could use: 「出社時刻を打刻して」、「タイムカードを[打]{う}って」(if they use a time card), etc.
{ "pile_set_name": "StackExchange" }
Q: How to query SQL Server table with XML column (as string) using Linq to SQL? How can I use LINQ to SQL to query a table with an XML datatype column as an IQueryable? SQL Server table: Id [int] SomeData [xml] An example of SomeData could be: <container><Person>Joe Smith</person></container> In T-SQL, I can query the table like this to find employees with a specific nam,e : SELECT * FROM [MyTable] WHERE SomeData.value('(//*[local-name()="Person"])[1]', 'varchar(max)') = 'Joe Smith' Or to treat the xml as a string, to search for a string regardless of xml schema: SELECT * FROM [MyTable] WHERE CONVERT(varchar(max), SomeData) like '%Joe Smith%' Now I turn to LINQ to SQL, and want to perform the second query: var myTable = db.MyTable.Where(x => x.SomeData.Value.Contains("Joe Smith")); I get the error: "The member 'System.Xml.Linq.XElement.Value' has no supported translation to SQL. I understand why I get the error, but is there a way to work around it? Being able to query the column as a string (with no concept of xml-structure) is completely fine in this case. A: Create a view that exposes the Xml column as varchar(...) and query that.
{ "pile_set_name": "StackExchange" }
Q: Nether Portal never goes to Nether I have a FTB Unleashed server, which I'm in the process of setting up before going public. Part of that setup is checking the Nether etc. So I built a Nether portal and strangely all it does is pass me around Nether Portals in the Overworld. What have I done wrong? The DIM1 folder is missing - so I suspect some generation is supposed to happen? A: In server.properties make sure Nether is enabled
{ "pile_set_name": "StackExchange" }
Q: read filters from a text file with tcpdump i would like to know as the title describes if there is a way read filters from a file in tcpdump currently i use tcpdump -r input.pcap -w output.pcap src host 1.1.1.1 and what i wan to do is make the tcpdump read the filter from a txt file, so the command would be something like tcpdump -r input.pcap -w output.pcap -filter myfilter.txt is there a way to do that? A: From a five seconds web search and the TCPDUMP man page OPTIONS -F file Use file as input for the filter expression. An additional expression given on the command line is ignored. A: It's not specifically about tcpdump but you can do this with any command whatsoever with standard Unix shell "backtick" $ tcpdump -r input.pcap -w output.pcap `cat myfilter.txt` The -F file method with a specific flag is better if the command has it, as tcpdump does, but the backtick method will work for anything.
{ "pile_set_name": "StackExchange" }
Q: Issues with dateformatter in iphone I am getting a NSDate *newDate value as 2011-08-12 13:00:00 +0000. Now when I try to convert it to a string by dateformatter as follows: NSDateFormatter *dateFormatter= [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd h:mm:ss Z"]; NSString *datestr = [[dateFormatter stringFromDate:newDate] lowercaseString];  But the value which I get for datestr is 5:30 hours more than the newDate value. I don't know where I am wrong. I get value for datestr as 2011-08-12 18:30:00 + 5:30 (which is incorrect). A: It is basically converting the time to your local time zone. if you dont want that just set the time aone for date formatter: [dateFormatter setTimeZone:[NSTimeZone <use any of the functions below to get your desired one>]]; Documentation link: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimeZone_Class/ Creating and Initializing Time Zone Objects + timeZoneWithAbbreviation: + timeZoneWithName: + timeZoneWithName:data: + timeZoneForSecondsFromGMT: – initWithName: – initWithName:data: + timeZoneDataVersion Working with System Time Zones + localTimeZone + defaultTimeZone + setDefaultTimeZone: + resetSystemTimeZone + systemTimeZone
{ "pile_set_name": "StackExchange" }
Q: When is the composition of a function and a harmonic function harmonic? I was looking at a comprehensive exam, and I found the this question. Can anyone help me out? If $u$ is a harmonic function, which type of function $f$ is needed so that $f(u)$ is harmonic? A: Note that $u$ is harmonic if and only if $$\Delta u:=\frac{\partial^2 u}{\partial x^2}+\frac{\partial^2 u}{\partial y^2}=0.$$ Therefore, if $u$ is harmonic, by chain rule we have $$\Delta f(u)=\frac{df}{du}\Big(\frac{\partial^2 u}{\partial x^2}+\frac{\partial^2 u}{\partial y^2}\Big)+\frac{d^2f}{du^2}\Big(\big(\frac{\partial u}{\partial x}\big)^2+\big(\frac{\partial u}{\partial y}\big)^2\Big)=\frac{d^2f}{du^2}\Big(\big(\frac{\partial u}{\partial x}\big)^2+\big(\frac{\partial u}{\partial y}\big)^2\Big).$$ If $u$ is a constant function (which is harmonic), then $\frac{\partial u}{\partial x}=\frac{\partial u}{\partial y}=0$. It follows from the above formula that $f(u)$ is harmonic for any function $f$. On the other hand, if $u$ is a nonconstant harmonic function, then $\big(\frac{\partial u}{\partial x}\big)^2+\big(\frac{\partial u}{\partial y}\big)^2\neq 0$. Again it follows from the above formula that $f(u)$ is harmonic when $\frac{d^2f}{du^2}=0$, that is, when $f$ is a linear function in $u$: $$f(u)=Au+B,$$ where $A$ and $B$ are constants.
{ "pile_set_name": "StackExchange" }
Q: How to use twitter REST api along with railscast 241 REST noob here: I'm using the code from ryan bates rails cast #241 http://railscasts.com/episodes/241-simple-omniauth I can authenticate with my user just fine.... Now I want to display the last tweet I made on the views/articles/index.html.erb page.... I want to just want to display the data from this REST api thing..."https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline" How do I change this code in the most simplest way? <% title "Articles" %> <div id="articles"> <!-- TODO grab my tweets with GET Statuses/home_timeline --> <% for article in @articles %> <h2> <%= link_to article.name, article %> <span class="comments">(<%= pluralize(article.comments.size, 'comment') %>)</span> </h2> <div class="created_at">on <%= article.created_at.strftime('%b %d, %Y') %></div> <div class="content"><%= simple_format(article.content) %></div> <% end %> </div> <p><%= link_to "New Article", new_article_path %></p> Thank you for help. A: You should take a loot at twitter gem: http://sferik.github.com/twitter/ You can grab a user's timeline like: timeline = Twitter.user_timeline( twitter_username )
{ "pile_set_name": "StackExchange" }
Q: ASHX handler; fires up only once I've got a simple ASHX handler that returns an dynamically generated image; the image is generated from a custom created class, and an object belonging to this class is passed to the handler using Session (I'd rather avoid using QueryString). The handler is used as the URL of an image on a ASP form which is very simple: a drop down list, a button and an image. Basically, depending on what the user selects from the list, the appropriate image will be generated once the button is pressed. At the start the actual image has it's Visible property set to false; I don't want the handler to display anything before the data is all there. Once the button is pressed, the required Session parameter is added containing the necessary object, and the page is refreshed using Server.Transfer. When the Page_load method detects that the Session parameter has been correctly set, it sets the Visible parameter on the image to true. After that the handler fires up and generates the image. So far so good... However, if the user now picks something different from the list and presses the button, despite the correct object being passed in the Session, the image won't be updated. In fact, the handler won't even fire up (if I put a breakpoint in there). I need to close the browser window and reopen it for it to work. Any ideas what could be the cause of such behaviour? I suspect the answer is very simple, and I just don't know something fundamental about ASP (or handlers)... A: The image is probably cached on the client and the browser didn't bother to request a new version from the server. At the beginning of the ProcessRequest method add: context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
{ "pile_set_name": "StackExchange" }
Q: Summing the values from the 2nd table based on ID of the 1st table and inserting values in first table How to in first table where it says UkupnaCena insert sum value of column Cena where RacunID in first table is equal to RacunID in other table. For example if RacunID is equal to 1 in first table, I want its UkupnaCena to be equal to sum of all values in column Cena where RacunID is 1. Tables: My procedure so far: Create procedure sp_RacunUpdate( @pRacunID int, @pStatusRacuna nvarchar(50), @pDatum nvarchar(20), @pOpis nvarchar(200), @pMesto nvarchar(50), @pKupacID int ) as begin Declare @pUkupnaCena decimal(20,2) select @pUkupnaCena=sum(Cena) from Stavka inner join Racun on Racun.RacunID=Stavka.RacunID Where Racun.RacunID=Stavka.RacunID group by Stavka.RacunID begin transaction UPDATE Racun SET StatusRacuna=@pStatusRacuna, Datum=@pDatum, Opis=@pOpis,Mesto=@pMesto,UkupnaCena=@pUkupnaCena,KupacID=@pKupacID WHERE RacunID=@pRacunID IF @@ERROR <> 0 BEGIN ROLLBACK END ELSE BEGIN COMMIT END END GO A: You can modify the update query to something like this UPDATE Racun from Racun SET UkupnaCena=(select sum(Cena) from Stavka s where s.RacunID= Racun.RacunID), Datum=@pDatum, Opis=@pOpis,Mesto=@pMesto,KupacID=@pKupacID WHERE RacunID=@pRacunID
{ "pile_set_name": "StackExchange" }
Q: Mounting single file in docker running on windows server 2019 (error: Invalid volume specification...) I am trying to run multiple Linux containers in Docker EE running on Windows server 2019. Everything is going well until I mount a single file to a container, like: VOLUME: - c:\xxx\yyy.xml:/app/yyy.xml When I spun up an instance I receive an error: ERROR: for xxx Cannot create container for service s1: invalid volume specification: 'C:\Users\xxx\yyy.xml:/app/yyy.xml' invalid mount config for type "bind": source path must be a directory Mounting a single file is possible in running Docker CE (on windows). Is there a way get this working without too many custom workarounds? A: Sadly no - Here is the link to the relevant issue on github. https://github.com/moby/moby/issues/30555 The gist of it... thaJeztah wrote Correct, bind-mounting files is not possible on Windows. On Linux, there's also quite some pitfalls though, so mounting a directory is preferred in many situations. However, Drewster727 pointed out the following For some context on my situtation-- We're running apps in the legacy .NET framework world (/sad-face) -- we have .config files mixed in with our application binaries. We don't want to build environment-specific containers, so of course, we try to share config files that have been transformed per environment directly inside the container to the location our application expects them. In case it helps anyone, I have a simple entrypoint.ps1 script hack to get around this issue for now. Share a directory to c:\conf with config files in it, the script will copy them into the app context folder on start: if(Test-Path c:\conf){ Copy-Item -path c:\conf*.* -Recurse -Destination . -Force }
{ "pile_set_name": "StackExchange" }
Q: How to create a file in java (not a folder) ? Perhaps somewhat embarassing, but after some hours I still cannot create a file in Java... File file = new File(dirName + "/" + fileName); try { // --> ** this statement gives an exception 'the system cannot find the path' file.createNewFile(); // --> ** this creates a folder also named a directory with the name fileName file.mkdirs(); System.out.println("file != null"); return file; } catch (Exception e) { System.out.println(e.getMessage()); return null; } What am I missing here? A: Try creating the parent dirs first: File file = new File(dirName + File.separator + fileName); try { file.getParentFile().mkdirs(); file.createNewFile(); System.out.println("file != null"); return file; } catch (Exception e) { System.out.println(e.getMessage()); return null; }
{ "pile_set_name": "StackExchange" }
Q: Manually configuring a new WCF endpoint I have a simple WCF service: namespace Vert.Host.VertService { [ServiceContract] public interface IRSVP { [OperationContract] bool Attending(); [OperationContract] bool NotAttending(); } public class RSVPService : IRSVP { public RSVPService() { } public bool Attending() { return true; } public bool NotAttending() { return true; } } } I'd like to self-host in a console application like so: class Program { public static void Main() { // Create a ServiceHost using (ServiceHost serviceHost = new ServiceHost(typeof(RSVPService))) { // Open the ServiceHost to create listeners // and start listening for messages. serviceHost.Open(); // The service can now be accessed. Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine(); } } } So I'm using this app.config <?xml version="1.0" encoding="utf-8"?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/> </startup> <system.serviceModel> <services> <service name="Vert.Host.VertService.RSVPService"> <host> <baseAddresses> <add baseAddress="http://localhost:8080/Vert" /> </baseAddresses> </host> <endpoint address="/RSVP" binding="basicHttpBinding" contract="Vert.Host.VertService.IRSVP" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpsGetEnabled="true" httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> As I understand it, this setup would leave me with http://localhost:8080/Vert/RSVP/Attending as a valid REST URI to call from an arbitrary HTTPClient, but the call is hanging indefinitely or coming back with a 0 No Response (I'm using Advanced REST client) What am I missing? A: You are RIGHT in all of your setup...right up to the point where you stopped typing code and started telling me what you have. :) What you've created is a std WCF service and you can get to it using a Service proxy or a ChannelFactory, but it will communicate with you as-is using SOAP. You need this tutorial to turn this webservice into a RESTFUL service giving back Json/pox.
{ "pile_set_name": "StackExchange" }
Q: lining up printfs to look nice and line them up How in the world do you format this for things to line up, ive tried everything, nothing changes?! printf("N Count\n"); printf("---- ------ \n"); for(i = 0 ; i < MAX_ELEMENTS ; i++) { count = getOccur(arr, MAX_ELEMENTS, arr[i]); printf("%1d %1d\n", arr[i], count); } I've tried tabbing, spacing, those % signs with the numbers for the last one, it wont change from this N Count ----- --- 1 1 2 1 3 1 Driving me crazy! I dont get it! lol EDIT WHOLE PROGRAM NEW QUESTION! #include <stdio.h> #define MAX_ELEMENTS 10 int getOccur(int a[], int num_elements, int value); void printArr(int a[], int num_elements); int main() { int arr[MAX_ELEMENTS]; int trim[MAX_ELEMENTS]; int count, target, i; int j, k, temp; for(i = 0 ; i < MAX_ELEMENTS ; i++) { printf("Enter a variable for the array: "); scanf("%d", &arr[i]); } for (j = 1 ; j <= MAX_ELEMENTS-1 ; j++) { for(k = 0 ; k <= MAX_ELEMENTS-2 ; k++) { if(arr[k] > arr[k+1]) { temp = arr[k]; arr[k] = arr[k+1]; arr[k+1] = temp; } } } printf("%4s %6s\n", " N ", "Count"); printf("%4s %6s\n", "----", "------"); for(i = 0 ; i < MAX_ELEMENTS ; i++) { count = getOccur(arr, MAX_ELEMENTS, arr[i]); printf("%3d %4d\n", arr[i], count); } } int getOccur(int a[], int tally, int value) { int i; tally = 0; for( i = 0 ; i < MAX_ELEMENTS ; i++) { if (a[i] == value) { ++tally; } } return(tally); } void printArr(int a[], int amount) { int i; for(i = 0 ; i < amount ; i++) { printf("%d ", a[i]); } printf("\n"); } A: printf("%4s %6s\n", " N ", "Count"); printf("%4s %6s\n", "----", "------"); for(i = 0 ; i < MAX_ELEMENTS ; i++) { count = getOccur(arr, MAX_ELEMENTS, arr[i]); printf("%4d %6d\n", arr[i], count); } That should line everything up. EDIT In response to the question in the comments, my approach would be to first find all the unique values in arr and save them to a different array (call it unique). Then you'd walk through the unique array in your loop: for (i = 0; i < uniqueCount; i++) { count = getOccur(arr, MAX_ELEMENTS, unique[i]); printf("%4d %6d\n", unique[i], count); } As for finding unique elements, the brute force method would be something like size_t uniqueCount = 0; int unique[MAX_SIZE]; // needs to be same size as original array in case // all values are unique for (i = 0; i < MAX_SIZE; i++) { size_t j = 0; for (j = 0; j < uniqueCount; j++) if (arr[i] == unique[j]) break; if (j == uniqueCount) unique[uniqueCount++] = arr[i]; } For each element in the original array, we scan the (initially empty) unique array. If we don't find the value of a[i] in the unique array, we add it and increment uniqueCount. Note that this method is pretty inefficient and will perform poorly as MAX_ELEMENTS gets large. Better solutions are available, but you sound like you're still at the bottom of the learning curve, so I'll leave it at that.
{ "pile_set_name": "StackExchange" }
Q: Drush for Drupal 4.7 I'm trying to find a version of Drush that is compatible with Drupal 4.7. I know it's old and lame and long time ago deprecated but I really need it for a project I'm currently involved in. I've tried to search it but without any luck. Thanks, Alex A: You can find it in the last page of the releases for drush on drupal.org (right at the bottom, unsurprisingly). As Greg mentions in the comments, Drush 1.x is a module so it needs to be put in the modules folder and enabled.
{ "pile_set_name": "StackExchange" }