text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How to construct WMI query
I'd like to find results that Name starts with param1, and ends with param2 but my code doesn't work
string wmiQuery = string.Format("SELECT CommandLine FROM Win32_Process WHERE Name LIKE '{0}%' AND Name LIKE '%{1}'", param1, param2);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection retObjectCollection = searcher.Get();
What's wrong?
For comparision
string wmiQuery = string.Format("SELECT CommandLine FROM Win32_Process WHERE Name LIKE '{0}%'", param1);
works well
A:
Try this:
string wmiQuery = string.Format("SELECT CommandLine FROM Win32_Process WHERE Name LIKE '{0}%{1}'", param1, param2);
Adding some test info:
string wmiQuery = string.Format ( "SELECT Name, ProcessID FROM Win32_Process WHERE Name LIKE '{0}%{1}'", "wpf", ".exe" );
Console.WriteLine ( "Query: {0}", wmiQuery );
ManagementObjectSearcher searcher = new ManagementObjectSearcher ( wmiQuery );
ManagementObjectCollection retObjectCollection = searcher.Get ( );
foreach (ManagementObject retObject in retObjectCollection)
{
Console.WriteLine ( "[{0}]\tName: {1}", retObject[ "ProcessID" ], retObject["Name"] );
}
Output:
Query: SELECT Name, ProcessID FROM
Win32_Process WHERE Name LIKE
'wpf%.exe'
[896] Name: WPFFontCache_v0400.exe
A:
To build WMI queries use a free tool from Microsoft known as WMI Code Creator in different programming languages VBS, VB.NET, C#
Download it from http://www.microsoft.com/downloads/en/details.aspx?familyid=2cc30a64-ea15-4661-8da4-55bbc145c30e&displaylang=en
| {
"pile_set_name": "StackExchange"
} |
Q:
"ActiveX component can't create object" in Access 2000 VBA app
I've got a VBA application that throws an "ActiveX component can't create object" exception when trying to run.
The breakpoint is set on the line that throws the exception:
I'm assuming that it has something to do with Me.Recordset (Me being the Access form). The recordset is probably related to the Microsoft DAO Library, which is referenced. Here are the current references:
The application is running on a Windows 98 machine, and the Access .mdb allegedly ran fine before (noone remembers what other computer it was originally on or the configuration of it. The form itself just scrolls through records of data (which works fine), but when firing the above Calc_Confidence_Level() subroutine, it tosses an error on the recordset that I thought would be the same one that it was scrolling through.
Does anyone know what's going wrong here? Even a push in the right direct to be able to debug this better would be great, as I don't exactly work with VBA/Access very often.
Thanks!
Update 1
I looked in "C:\Program Files\Common Files\microsoft shared\DAO\" and don't see a .dll at all, only a .tlb file. There should be a .dll in there, right?
A:
You should make clear if (1) you have an active recordset in your form, and then (2) if your recordset is an ADODB one, or a DAO one. Usually, when a form is open the standard way (with a 'recordsource' property referring to a local\linked table or view), the recordset is of the DAO type. In these conditions, you need the DAO library. If there is no 'recordsource' property for the form, there is no recordset, or it has to be set 'on the fly', for example in the 'on open' event. You then have to check what kind of recordset is declared in the proc. ('findfirst' is a DAO method, that cannot be used with ADODB recordsets)
Another thing could be to make sure that the form is not corrupted: open a new\empty database, import all objects from your active database, and test it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are Python classes in Spark notebooks beneficial or common in the data scientist community?
Being a software developer, I am coming from an object-oriented programming background, and I think in terms of classes and objects.
I am currently working on a Spark notebook to perform calculations on a dataset, for which I am following a more procedural approach (i.e. adding new columns to a dataframe as I perform the calculations.)
My question is if it is common among data scientists to use classes in their Spark notebooks to encapsulate functionality as opposed to following a more procedural approach.
A:
In general you are writing pipelines and you relay on fact that "you run n+1 cell only if previous n completed with success" and you don't have to rely on super structurized code. On the other hand you want to have some functionalities closed in classes/functions and then run them with different parameters, but don't stick too much to classes since 90% of work is prototyping. After all if you written your code in propper way making it as class shouldn't be much of a hassle, so code should be clean and clear but structurizing it makes iterations very slow.
So rule of a thumb you close code into class only when you want to reuse it and you are sure it will remain like this for very long time
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there any modules where you can import H2Database data into drupal 7 as nodes?
I'm working with the java h2 database engine and there is data that i want to query/import everyday. Is there a module or how would I go about importing such data into drupal 7 as nodes?
A:
Your best bet is likely to use the Migrate module and a custom php H2 database driver.
This is not easy.
You can follow this to get php working with PDO and Java H2. http://www.webdevelopersdiary.com/1/post/2012/07/jamp-an-ultra-portable-php-web-server-and-database-stack-in-java.html
From there you will need to write a class for the migrate module that extends the migrate source class
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does the Rich Text Box freeze when loading a large string?
I have a program where I basically need to load Rich Text from a StringBuilder.
The problem is, somethimes I get a string that is 100,000 lines long (and this is a possible situation for the program), including Rtf codes and colours.
The problem isn't building the string, it's when I asign the Rtf property to the StringBuilder.ToString(), it takes a solid 4 minutes to load.
TextBox.Rtf = Build.ToString();
If I copy this same string from the StringBuilder, and load it in WordPad, it takes about 2 or 3 seconds. I am diabling the RTB's redrawing by using SendMessage() and WM_SETREDRAW, but that doesn't change anything.
Any suggestions?
A:
RichTextBox uses riched20.dll which is the v3.0 of the library Rich Edit Control of Microsoft. However, WordPad uses msfedit.dll which is version 4.1.
Version 4.1 is about 30 times more faster than v3.0
See this for more information about versions
MSDN About Rich Edit Controls
| {
"pile_set_name": "StackExchange"
} |
Q:
Removing grid from scanned image
I have to recognize the text of the hand-filled bank form. The form has a grid as shown in the image. I am new to Image Processing. I read few papers on handwriting recognition and did denoising, binarization as preprocessing tasks. I want to segment the image now and recognize the characters using a Neural Network. To segment the characters I want to get rid of the grid.
Thank you very much in advance.
A:
I have a solution using OpenCV.
First, I inverted the image:
ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
Now I performed morphological opening operation:
opening = cv2.morphologyEx(thresh2, cv2.MORPH_OPEN, k2)
cv2.imshow('opening', opening)
You can see that the grid lines have disappeared. But there are some gaos in some of the characters as well. So to fill the gaps I performed morphological dilation operation:
dilate = cv2.morphologyEx(opening, cv2.MORPH_DILATE, k1)
cv2.imshow('dilation', dilate)
You can check out THIS LINK for more morphological operations and kernels used.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to typecast byte array to 8 byte-size integer
I was asked an interview question: given a 6 byte input, which got from a big endian machine, please implement a function to convert/typecast it to 8 bytes, assume we do not know the endian of the machine running this function.
The point of the question seems to test my understanding of endianess because I was asked whether I know endianess before this question.
I do not know how to answer the question. e.g. do I need to pad 6 byte to 8 byte first? and how? Here is my code. is it correct?
bool isBigEndian(){
int num = 1;
char* b = (char*)(&num);
return b ? false:true;
}
long long* convert(char* arr[]){ //size is 6
long long* res = (long long*)malloc(long long);//...check res is NULL...
if (isBigEnian()){
for(int i = 0; i< 6; i++)
memset(res, i+2, arr[i]);
}
else {
for(int i = 0; i< 6; i++)
memset(res, i+2, arr[6-1-i]);
}
return res; //assume caller will free res.
}
update: to answer that my question is not clear, I just found a link: Convert Bytes to Int / uint in C with the similar question. based on my understanding of that, endianess of the host does matters. suppose if input is: char array[] = {01,02,03,04,05,06}, then if host is little endian, output is stored as 00,00,06,05,04,03,02,01, if big endian, output will be stored as 00,00,01,02,03,04,05,06, in both case, the 0000 are padded at beginning.
I am a kind of understand now: in the other machine, suppose there is a number xyz = 010203040506 because it is bigendian and 01 is MSB. so it is stored as char array = {01,02,03,04,05,06} where 01 has lowest address. then in this machine, if the machine is also big endian. it should be stored as {00,00,01,02,03,04,05,06 } where 01 is still MSB, so that it is cast to the same number int_64 xyz2 = 0000010203040506. but if the machine is little endian, it should be stored as {00,00,06,05,04,03,02,01 } where 01 is MSB has highest address in order for int_32 xyz2 = 0000010203040506.
please let me know if my undestanding is incorrect. and Can anybody tell me why 0000 is always padded at beginning no matter what endianess? shouldn't it be padded at the end if this machine is little endian since 00 is Most sign byte?
A:
Before moving on, you should have asked for clarification.
What exactly means converting here? Padding each char with 0's? Prefixing each char with 0's?
I will assume that each char should be prefixed with 0's. This is a possible solution:
#include <stdint.h>
#include <limits.h>
#define DATA_WIDTH 6
uint64_t convert(unsigned char data[]) {
uint64_t res;
int i;
res = 0;
for (i = 0; i < DATA_WIDTH; i++) {
res = (res << CHAR_BIT) | data[i];
}
return res;
}
To append 0's to each char, we could, instead, use this inside the for:
res = (res << CHAR_BIT) | (data[i] << 2);
In an interview, you should always note the limitations for your solution. This solution assumes that the implementation provides uint64_t type (it is not required by the C standard).
The fact that the input is big endian is important because it lets you know that data[0] corresponds to the most significant byte, and it must remain so in your result. This solution works not matter what the target machine's endianness.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android NFC Redirecting intent
When i put an nfc tag close to my mobile phone i want my app to start
so i added this into my manifest:
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/nfc_tech_filter" />
This works great.
If a user is not logged in i want the user to log in first before
he can transfer the data from the tag so i added this into my
onCreate of my measure activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.sessionManager = new SessionManager(this);
this.sessionManager.login();
this.setContentView(R.layout.activity_measure);
this.nfcAdapter = NfcAdapter.getDefaultAdapter(this);
this.pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
this.filters = new IntentFilter[] { ndef, };
this.techLists = new String[][] { new String[] { android.nfc.tech.NfcV.class.getName() } };
this.textViewYear = (TextView) findViewById(R.id.measure_textview_year);
this.textViewMonthDay = (TextView) findViewById(R.id.measure_textview_month_day);
this.textViewTime = (TextView) findViewById(R.id.measure_textview_time);
this.textViewGlucose = (TextView) findViewById(R.id.measure_textview_glucose);
new StartReadTask().execute();
}
But after the user is logged in he gets redirected to my main menu because of this
implementation:
/**
*
* @param v
*/
@Override
public void onClick(View view) {
String username = this.textEditUsername.getText().toString();
String password = this.textEditPassword.getText().toString();
if(username.trim().length() > 0 && password.trim().length() > 0){
if(username.equals("test") && password.equals("test")){
this.sessionManager.createLoginSession("Test-Name", "Test-Email");
Intent intent = new Intent(this.getApplicationContext(), MainActivity.class);
this.startActivity(intent);
this.finish();
} else {
this.dialogAlertManager.showAlertDialog(LoginActivity.this, "Login failed..", "Username or Password is incorrect", false);
}
} else {
this.dialogAlertManager.showAlertDialog(LoginActivity.this, "Login failed..", "Please enter username and password", false);
}
}
The 'MainActivity' mentioned here is my main menu. but i want the activity to
redirect to my measure activity but i don't know how i can do that. after a
"normal" login, without nfc intent, i need the app to redirect to the main menu
but with nfc intent i want it to redirect to the measure activity.
Also when the user already is logged in i want the data of the tag to be transferred
immediately. now if i want to transfer the data i have to keep the tag close to the
phone to start the measure activity and than to put it away and back again to
transfer the data.
How can i do both things?
A:
You are doing to many different things in the same code: reading nfc, accessing ui fields, controlling the flows of the activities. (Yes, android sample code often give bad examples)
You need to handle special cases like what is happening when the user just starts to login an then the tag is read. Your only chance to get this right is to separate the different responsibilities in your code.
One thing is sure: you need to store the information when a tag was read. So you can react differently and finally display it when the user has logged in. When there are different Activities involved, you probably need to store the data in some kind of central entity, like a singleton. (Alternative is to always send the information together with the intent when you move from activity to another)
For NFC-reading, there is an example app "NFC-HUNT" from google which I found helpful.
The has some special features:
it uses a special activity without UI that reads the NFC-Tag. This way NFC-reading is encapsulated, and the rest of your app has no NFC-Code at all. This Activty (called NFCShimActivity) just ready the Infomation and then creates an Intent to start your normal UI.
Normally, when an Activity is visible and new Intent for this Activity arrives (because NFC-Tag was read), another instance of the Actiity gets opened. Just what you do not want.
Solution is to set android:launchMode="singleTask" in Manifest, and to implement this method in the Activity:
public void onNewIntent(Intent intent) {...}
I have written a blog entry about the nfc code reading structure, maybe it helps you to make it easier to understand
http://meier-online.com/en/2014/09/nfc-hunt-analysed/
| {
"pile_set_name": "StackExchange"
} |
Q:
What are differences between delete(Iterable itrbl) in CrudRepository and deleteInBatch(Iterable itrbl) in JpaRepository
I'm getting an issues when trying to delete a list of entities which have a foreign key. A delete method in CrudRepository work fine with table doesn't have foreign key but when I tried to delete a list of entities have foreign key, it reported success but nothing was delete in database. The deleteInBatch() work fine in both.
What is differences between the method delete(Iterable<? extends T> itrbl) in CrudRepository and deleteInBatch(Iterable<T> itrbl) in JpaRepository?
I have gone through this.
Any help would be appreciated
My model SmsNotifyTemplate.java:
package com.viettel.pcrf.webconfig.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Anh Nguyen
*/
@Entity
@Table(name = "SMS_NOTIFY_TEMPLATE", catalog = "", schema = "VPCRF")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "SmsNotifyTemplate.findAll", query = "SELECT s FROM SmsNotifyTemplate s"),
@NamedQuery(name = "SmsNotifyTemplate.findBySmsNotifyTemplateId", query = "SELECT s FROM SmsNotifyTemplate s WHERE s.smsNotifyTemplateId = :smsNotifyTemplateId"),
@NamedQuery(name = "SmsNotifyTemplate.findByMessageTemplate", query = "SELECT s FROM SmsNotifyTemplate s WHERE s.messageTemplate = :messageTemplate"),
@NamedQuery(name = "SmsNotifyTemplate.findByComments", query = "SELECT s FROM SmsNotifyTemplate s WHERE s.comments = :comments"),
@NamedQuery(name = "SmsNotifyTemplate.findBySmsTemplateCode", query = "SELECT s FROM SmsNotifyTemplate s WHERE s.smsTemplateCode = :smsTemplateCode")})
public class SmsNotifyTemplate implements Serializable {
public static enum COLUMNS {
COMMENTS, LANGID, MESSAGETEMPLATE, SMSNOTIFYTEMPLATEID, SMSTEMPLATECODE
};
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "SMS_NOTIFY_TEMPLATE_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO, generator = "sms_notify_template_seq_gen")
@SequenceGenerator(name = "sms_notify_template_seq_gen", sequenceName = "SMS_NOTIFY_TEMPLATE_SEQ")
private Short smsNotifyTemplateId;
@Column(name = "MESSAGE_TEMPLATE", length = 480)
private String messageTemplate;
@Column(name = "COMMENTS", length = 200)
private String comments;
@Column(name = "SMS_TEMPLATE_CODE")
private Integer smsTemplateCode;
@JoinColumn(name = "LANG_ID", referencedColumnName = "LANG_ID", nullable = false)
@ManyToOne(optional = false)
private Lang langId;
public SmsNotifyTemplate() {
}
public SmsNotifyTemplate(Short smsNotifyTemplateId) {
this.smsNotifyTemplateId = smsNotifyTemplateId;
}
public Short getSmsNotifyTemplateId() {
return smsNotifyTemplateId;
}
public void setSmsNotifyTemplateId(Short smsNotifyTemplateId) {
this.smsNotifyTemplateId = smsNotifyTemplateId;
}
public String getMessageTemplate() {
return messageTemplate;
}
public void setMessageTemplate(String messageTemplate) {
this.messageTemplate = messageTemplate;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Integer getSmsTemplateCode() {
return smsTemplateCode;
}
public void setSmsTemplateCode(Integer smsTemplateCode) {
this.smsTemplateCode = smsTemplateCode;
}
public Lang getLangId() {
return langId;
}
public void setLangId(Lang langId) {
this.langId = langId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (smsNotifyTemplateId != null ? smsNotifyTemplateId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof SmsNotifyTemplate)) {
return false;
}
SmsNotifyTemplate other = (SmsNotifyTemplate) object;
return !((this.smsNotifyTemplateId == null && other.smsNotifyTemplateId != null) || (this.smsNotifyTemplateId != null && !this.smsNotifyTemplateId.equals(other.smsNotifyTemplateId)));
}
@Override
public String toString() {
return "com.viettel.pcrf.model.SmsNotifyTemplate[ smsNotifyTemplateId=" + smsNotifyTemplateId + " ]";
}
}
I have a mapper to map the model with a normal class:
SmsTemplateMapper.java:
package com.viettel.pcrf.webconfig.mapper;
import com.viettel.fw.common.util.mapper.BaseMapper;
import com.viettel.pcrf.webconfig.dto.SmsTemplateDTO;
import com.viettel.pcrf.webconfig.model.SmsNotifyTemplate;
public class SmsTemplateMapper extends BaseMapper<SmsNotifyTemplate, SmsTemplateDTO> {
@Override
public SmsTemplateDTO toDtoBean(SmsNotifyTemplate model) {
SmsTemplateDTO obj = null;
if (model != null) {
obj = new SmsTemplateDTO();
obj.setComments(model.getComments());
obj.setMessageTemplate(model.getMessageTemplate());
obj.setSmsNotifyTemplateId(model.getSmsNotifyTemplateId());
obj.setSmsTemplateCode(model.getSmsTemplateCode());
obj.setLangId(model.getLangId());
}
return obj;
}
@Override
public SmsNotifyTemplate toPersistenceBean(SmsTemplateDTO dtoBean) {
SmsNotifyTemplate obj = null;
if (dtoBean != null) {
obj = new SmsNotifyTemplate();
obj.setComments(dtoBean.getComments());
obj.setMessageTemplate(dtoBean.getMessageTemplate());
obj.setSmsNotifyTemplateId(dtoBean.getSmsNotifyTemplateId());
obj.setSmsTemplateCode(dtoBean.getSmsTemplateCode());
obj.setLangId(dtoBean.getLangId());
System.out.println(obj.getLangId().getNationality());
}
return obj;
}
}
SmsTemplateDTO.java:
package com.viettel.pcrf.webconfig.dto;
import com.viettel.fw.dto.BaseDTO;
import com.viettel.pcrf.webconfig.model.Lang;
import java.io.Serializable;
public class SmsTemplateDTO extends BaseDTO implements Serializable {
public String getKeySet() {
return keySet;
}
private String comments;
private String messageTemplate;
private Short smsNotifyTemplateId;
private Integer smsTemplateCode;
private Lang langId;
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getMessageTemplate() {
return this.messageTemplate;
}
public void setMessageTemplate(String messageTemplate) {
this.messageTemplate = messageTemplate;
}
public Short getSmsNotifyTemplateId() {
return this.smsNotifyTemplateId;
}
public void setSmsNotifyTemplateId(Short smsNotifyTemplateId) {
this.smsNotifyTemplateId = smsNotifyTemplateId;
}
public Integer getSmsTemplateCode() {
return this.smsTemplateCode;
}
public void setSmsTemplateCode(Integer smsTemplateCode) {
this.smsTemplateCode = smsTemplateCode;
}
public Lang getLangId() {
return langId;
}
public void setLangId(Lang langId) {
this.langId = langId;
}
}
SmsTemplateRepo.java:
package com.viettel.pcrf.webconfig.repo;
import com.viettel.fw.persistence.BaseRepository;
import java.util.List;
import com.viettel.pcrf.webconfig.model.SmsNotifyTemplate;
public interface SmsTemplateRepo extends BaseRepository<SmsNotifyTemplate>, SmsTemplateRepoCustom {
public List<SmsNotifyTemplate> findByComments(String comments);
public List<SmsNotifyTemplate> findByMessageTemplate(String messageTemplate);
public List<SmsNotifyTemplate> findBySmsNotifyTemplateId(Short smsNotifyTemplateId);
public List<SmsNotifyTemplate> findBySmsTemplateCode(Integer smsTemplateCode);
}
BaseRepository extends JpaRepository.
A delete method will be in deleteSmsNotifyTemplates method in this class:
SmsTemplateServiceImpl.java:
package com.viettel.pcrf.webconfig.service;
import com.viettel.fw.common.util.extjs.FilterRequest;
import com.viettel.fw.dto.BaseMessage;
import com.viettel.pcrf.webconfig.repo.SmsTemplateRepo;
import com.viettel.pcrf.webconfig.mapper.SmsTemplateMapper;
import com.viettel.pcrf.webconfig.dto.SmsTemplateDTO;
import com.viettel.pcrf.webconfig.model.SmsNotifyTemplate;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
*
* @author Anh Nguyen
*/
@Service
public class SmsTemplateServiceImpl extends BaseServiceImpl implements SmsTemplateService {
private final SmsTemplateMapper mapper = new SmsTemplateMapper();
@Autowired
private SmsTemplateRepo repository;
public Logger logger = Logger.getLogger(SmsTemplateService.class);
@Override
public BaseMessage deleteSmsNotifyTemplates(List<SmsTemplateDTO> smsNotifyTemplateDTOs) throws Exception {
BaseMessage baseMessage = new BaseMessage();
repository.delete(mapper.toPersistenceBean(smsNotifyTemplateDTOs));
baseMessage.setSuccess(true);
baseMessage.setOutputObject(smsNotifyTemplateDTOs);
return baseMessage;
}
}
The Controller:
SmsTemplateCtrl.java:
package com.viettel.pcrf.webconfig.controller;
import com.viettel.fw.Exception.LogicException;
import com.viettel.fw.common.util.extjs.FilterRequest;
import com.viettel.fw.web.controller.BaseController;
import com.viettel.pcrf.webconfig.dto.LangDTO;
import com.viettel.pcrf.webconfig.dto.SmsTemplateDTO;
import com.viettel.pcrf.webconfig.model.Lang;
import com.viettel.pcrf.webconfig.service.LangService;
import com.viettel.pcrf.webconfig.service.SmsTemplateService;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
*
* @author Anh Nguyen
*/
@Component("smsNotifyTemplateController")
@Scope("view")
public class SmsTemplateCtrl extends BaseController implements Serializable {
private List<SmsTemplateDTO> listSmsNotifyTemplate;
private SmsTemplateDTO smsNotifyTemplate;
private List<SmsTemplateDTO> selectedSmsNotifyTemplates;
private List<LangDTO> listLang;
@Autowired
private SmsTemplateService smsNotifyTemplateService;
@Autowired
private LangService langService;
public List<SmsTemplateDTO> getListSmsNotifyTemplate() {
return listSmsNotifyTemplate;
}
public void setListSmsNotifyTemplate(List<SmsTemplateDTO> listSmsNotifyTemplate) {
this.listSmsNotifyTemplate = listSmsNotifyTemplate;
}
public SmsTemplateDTO getSmsNotifyTemplate() {
return smsNotifyTemplate;
}
public void setSmsNotifyTemplate(SmsTemplateDTO smsNotifyTemplate) {
this.smsNotifyTemplate = smsNotifyTemplate;
}
public List<SmsTemplateDTO> getSelectedSmsNotifyTemplates() {
return selectedSmsNotifyTemplates;
}
public void setSelectedSmsNotifyTemplates(List<SmsTemplateDTO> selectedSmsNotifyTemplates) {
this.selectedSmsNotifyTemplates = selectedSmsNotifyTemplates;
}
public List<LangDTO> getListLang() {
return listLang;
}
public void setListLang(List<LangDTO> listLang) {
this.listLang = listLang;
}
/**
* Khoi Tao Cac doi tuong de load len view
*/
@PostConstruct
public void init() {
listSmsNotifyTemplate = smsNotifyTemplateService.findAllSort();
listLang = langService.findAllSort();
formStatus = getFormStatus();
}
/**
* Chuan bi cho thao tac delete
*/
public void delete() {
try {
if (selectedSmsNotifyTemplates == null || selectedSmsNotifyTemplates.isEmpty()) {
reportError("msgInfo", "Choose one row!");
} else {
smsNotifyTemplateService.deleteSmsNotifyTemplates(selectedSmsNotifyTemplates);
reportSuccess("msgInfo", "common.msg.success.delete");
reset();
updateController();
}
} catch (LogicException logicE) {
reportError("msgInfo", logicE);
} catch (Exception exception) {
reportError("msgInfo", exception.getMessage());
}
}
/**
* Kiem tra SmsNotifyTemplateId ton tai trong bang SMS_NOTIFY_TEMPLATE
*
* @param smsNotifyTemplates
* @return
*/
public boolean SmsNotifyTemplateIdExistedInSmsNotifyTemplate(List<SmsTemplateDTO> smsNotifyTemplates) {
List<FilterRequest> listReq = new ArrayList<>();
for (SmsTemplateDTO s : smsNotifyTemplates) {
listReq.add(new FilterRequest("LANGID", s.getLangId()));
}
List<SmsTemplateDTO> list = smsNotifyTemplateService.findAll(listReq);
return !list.isEmpty();
}
/**
* Kiem tra SmsNotifyTemplateCode ton tai trong bang LANG
*
* @param smsTemplateCode
* @param smsNotifyTemplateId
* @return
*/
public boolean SmsTemplateCodeExisted(Integer smsTemplateCode, Short smsNotifyTemplateId) {
List<FilterRequest> listReq = new ArrayList<>();
listReq.add(new FilterRequest("SMSTEMPLATECODE", smsTemplateCode));
List<SmsTemplateDTO> list = smsNotifyTemplateService.findAll(listReq);
if (list.isEmpty()) {
return false;
}
if (list.size() > 1) {
return true;
} else {
return !list.get(0).getSmsNotifyTemplateId().equals(smsNotifyTemplateId);
}
}
}
And the xhtml page. I'm using primefaces framework.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<ui:composition template="../../templates/layoutTemplate.xhtml" >
<ui:define name="title">SMS Notify Template Configuration</ui:define>
<ui:define name="featureName">SMS Notify Template Configuration</ui:define>
<ui:define name="content">
<h:form id="frmSmsNotifyTemplate">
<p:dataTable var="tabSmsNotifyTemplate"
id="smsNotifyTemplateList"
value="#{smsNotifyTemplateController.listSmsNotifyTemplate}"
selection="#{smsNotifyTemplateController.selectedSmsNotifyTemplates}"
rowsPerPageTemplate="5,10,15,20,50"
paginatorPosition="bottom"
paginator="true"
rows="10"
paginatorAlwaysVisible="false"
sortMode="single"
sortBy="#{tabSmsNotifyTemplate.smsNotifyTemplateId}"
rowKey="#{tabSmsNotifyTemplate.smsNotifyTemplateId}" >
<p:column selectionMode="multiple" style="width:16px;text-align:center" />
<p:ajax event="toggleSelect" update="@([id$=btnEdit]) @([id$=btnDelete])" />
<p:ajax event="rowSelect" update="@([id$=btnEdit]) @([id$=btnDelete])" />
<p:ajax event="rowSelectCheckbox" update="@([id$=btnEdit]) @([id$=btnDelete])" />
<p:ajax event="rowUnselectCheckbox" update="@([id$=btnEdit]) @([id$=btnDelete])" />
<p:column headerText="ID" style="width: 100px;">
<h:outputText value="#{tabSmsNotifyTemplate.smsNotifyTemplateId}" />
</p:column>
<p:column headerText="Message Template" style="width: 100px;" sortBy="#{tabSmsNotifyTemplate.messageTemplate}">
<h:outputText value="#{tabSmsNotifyTemplate.messageTemplate}" />
</p:column>
<p:column headerText="SMS Template Code" sortBy="#{tabSmsNotifyTemplate.smsTemplateCode}">
<h:outputText value="#{tabSmsNotifyTemplate.smsTemplateCode}" />
</p:column>
<p:column headerText="Language" sortBy="#{tabSmsNotifyTemplate.langId.nationality}">
<h:outputText value="#{tabSmsNotifyTemplate.langId.nationality}" />
</p:column>
<p:column headerText="Comments" sortBy="#{tabSmsNotifyTemplate.comments}">
<h:outputText value="#{tabSmsNotifyTemplate.comments}" />
</p:column>
<f:facet name="footer">
<div align="left">
<span class="vt-button">
<p:commandLink
action="#{smsNotifyTemplateController.prepareInsert()}"
process="smsNotifyTemplateList"
update="@form"
resetValues="true"
style="margin-right:30px;border: none">
<p:graphicImage style="width:10px;height:10px;"
value="/resources/themes/images/icon-add.png"/>
<span class="vt-button-text">
<h:outputText value="#{lang['common.button.add']}"/>
</span>
<f:setPropertyActionListener
target="#{smsNotifyTemplateController.formStatus}"
value="#{vpcrfConst.BTN_ADD}"/>
</p:commandLink>
<p:commandLink
id="btnEdit"
action="#{smsNotifyTemplateController.prepareEdit()}"
process="smsNotifyTemplateList"
update="@form"
disabled="#{smsNotifyTemplateController.selectedSmsNotifyTemplates.size()>1 or smsNotifyTemplateController.selectedSmsNotifyTemplates==null or smsNotifyTemplateController.selectedSmsNotifyTemplates.size()==0}"
resetValues="true"
style="margin-right:30px;border: none">
<p:graphicImage style="width:10px;height:10px;"
value="/resources/themes/images/icon-edit.png"/>
<span class="vt-button-text">
<h:outputText value="#{lang['common.button.edit']}"/>
</span>
<f:setPropertyActionListener
target="#{smsNotifyTemplateController.formStatus}"
value="#{vpcrfConst.BTN_EDIT}"/>
</p:commandLink>
<p:commandLink
id="btnDelete"
action="#{smsNotifyTemplateController.delete()}"
immediate="true"
update="@form"
disabled="#{smsNotifyTemplateController.selectedSmsNotifyTemplates.size()==0 or smsNotifyTemplateController.selectedSmsNotifyTemplates==null}"
resetValues="true"
style="margin-right:30px;border: none">
<p:graphicImage style="width:10px;height:10px;"
value="/resources/themes/images/icon-delete.png"/>
<span class="vt-button-text">
<h:outputText value="#{lang['common.button.delete']}"/>
</span>
<p:confirm header="Delete" message="Are you sure? (Ok/Cancel)" icon="ui-icon-alert" />
</p:commandLink>
</span>
</div>
</f:facet>
</p:dataTable>
<p:growl id="testMsg" showSummary="false" showDetail="true" autoUpdate="true" sticky="true" />
<p:focus context="editPanel"/>
<p:fieldset legend="SMS Notify Template Detail" rendered="#{smsNotifyTemplateController.smsNotifyTemplate!=null}">
<h:panelGrid id="editPanel"
columnClasses="vocs-120, vocs-300"
columns="2" rendered="#{smsNotifyTemplateController.smsNotifyTemplate!=null}">
<p:outputLabel for="smsID" value="ID" />
<p:inputText id="smsID"
value="#{smsNotifyTemplateController.smsNotifyTemplate.smsNotifyTemplateId}"
required="true"
maxlength="15"
disabled="true"
style="min-width: 300px;"/>
<p:outputLabel for="messTemplate" value="Message Template" />
<p:inputText id="messTemplate"
value="#{smsNotifyTemplateController.smsNotifyTemplate.messageTemplate}"
required="true"
maxlength="60"
style="min-width: 300px;"/>
<p:outputLabel for="langId" value="SMS Notify Template" />
<p:selectOneMenu id="langId"
required="true"
value="#{smsNotifyTemplateController.smsNotifyTemplate.langId.langId}"
style="width: 306px;">
<f:selectItem itemLabel="Select Language"
itemDisabled="true"
noSelectionOption="true"/>
<f:selectItems value="#{smsNotifyTemplateController.listLang}"
var="l"
itemLabelEscaped="true"
itemValue="#{l.langId}"
itemLabel="#{l.nationality}" />
</p:selectOneMenu>
<p:outputLabel for="templateCode" value="Template Code" />
<p:inputTextarea id="templateCode"
value="#{smsNotifyTemplateController.smsNotifyTemplate.smsTemplateCode}"
required="true"
maxlength="10"
style="min-width: 300px;"/>
<p:outputLabel for="comments" value="Comments" />
<p:inputTextarea id="comments"
value="#{smsNotifyTemplateController.smsNotifyTemplate.comments}"
required="false"
maxlength="10"
style="min-width: 300px;"/>
<div />
<h:panelGroup>
<p:commandButton
value="OK"
process="editPanel"
rendered="#{smsNotifyTemplateController.formStatus==vpcrfConst.BTN_ADD}"
action="#{smsNotifyTemplateController.insert()}"
update="smsNotifyTemplateList,editPanel,@form" />
<p:commandButton rendered="#{smsNotifyTemplateController.formStatus==vpcrfConst.BTN_ADD}"
value="#{lang['common.button.reset']}"
immediate="true">
<p:ajax update="smsID,messTemplate,langId,templateCode,comments" resetValues="true" />
</p:commandButton>
<p:commandButton
value="OK"
rendered="#{smsNotifyTemplateController.formStatus==vpcrfConst.BTN_EDIT}"
action="#{smsNotifyTemplateController.update()}"
update="smsNotifyTemplateList,editPanel,@form" />
<p:commandButton rendered="#{smsNotifyTemplateController.formStatus==vpcrfConst.BTN_EDIT}"
value="#{lang['common.button.reset']}"
immediate="true"
action="#{smsNotifyTemplateController.clearInput()}"
update="smsID,messTemplate,langId,templateCode,comments"
resetValues="true"/>
<p:commandButton
value="#{lang['common.button.cancel']}"
action="#{smsNotifyTemplateController.reset()}"
immediate="true"
update="@form"/>
</h:panelGroup>
</h:panelGrid>
</p:fieldset>
</h:form>
</ui:define>
</ui:composition>
</html>
A:
The documentation explains the difference. deleteInBatch() does the following:
Deletes the given entities in a batch which means it will create a single Query. Assume that we will clear the EntityManager after the call.
whereas delete() does the following:
Deletes the given entities.
So, the fist one will execute a delete JPQL query like
delete from SomeEntity e where e.id in :ids
whereas the second one will loop through the entities and call
entityManager.remove(entity)
Both should work, whether your entity has a foreign key or not. The second one will apply cascades whereas the first one won't. It's impossible to tell why you're having this issue without knowing anything about your code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Extract sub-string between 2 special characters from one column of Pandas DataFrame
I have a Python Pandas DataFrame like this:
Name
Jim, Mr. Jones
Sara, Miss. Baker
Leila, Mrs. Jacob
Ramu, Master. Kuttan
I would like to extract only name title from Name column and copy it into a new column named Title. Output DataFrame looks like this:
Name Title
Jim, Mr. Jones Mr
Sara, Miss. Baker Miss
Leila, Mrs. Jacob Mrs
Ramu, Master. Kuttan Master
I am trying to find a solution with regex but failed to find a proper result.
A:
In [157]: df['Title'] = df.Name.str.extract(r',\s*([^\.]*)\s*\.', expand=False)
In [158]: df
Out[158]:
Name Title
0 Jim, Mr. Jones Mr
1 Sara, Miss. Baker Miss
2 Leila, Mrs. Jacob Mrs
3 Ramu, Master. Kuttan Master
or
In [163]: df['Title'] = df.Name.str.split(r'\s*,\s*|\s*\.\s*').str[1]
In [164]: df
Out[164]:
Name Title
0 Jim, Mr. Jones Mr
1 Sara, Miss. Baker Miss
2 Leila, Mrs. Jacob Mrs
3 Ramu, Master. Kuttan Master
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding critical points of $x^{(2/3)}(5-x)$
So I tried this out and got stuck with this:
$$0 = 3x^{(7/6)} + 2x - 10$$
I didn't think I could use a quadratic for this since its to the power of $7/6$
Here is the working I did:
We know its a critical point when f'(a) = 0
So I found the derivative of f(x) which is $$2*(5-x)/3x^{1/2} - x ^{2/3}$$
So I set this equal to 0
$$2*(5-x)/3x^{1/2} - x ^{2/3} = 0$$
$$2*(5-x)/3x^{1/2}=x ^{2/3}$$
$$2*(5-x)=x ^{2/3}\times3x^{1/2}$$
$$10-2x=3x ^{2/3 +1/2}$$
$$10=3x ^{7/6} + 2x$$
But this would be such a messy answer, so I think I have done something wrong with my working. Do you have any ideas?
A:
If $$f(x) = x^{2/3}(5-x) =5x^{2/3}-x^{5/3},$$
then $$f'(x) = \frac{10}{3}x^{-1/3} - \frac{5}{3}x^{2/3}$$
Of course, to find critical points, we need to solve for
$$f'(x) = 0 \iff \frac{10}{3}x^{-1/3} = \frac{5}{3}x^{2/3}$$
Assuming if $x\neq 0$, multiply both sides of the equation by $\;\frac 35 x^{1/3}\;$ to find the solution. Note: Do check what happens at $x = 0$, where the function is defined, but not the derivative.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why setBaseSectionPaint doesn't work?
I have a pie chart. I need fill all section same color. In jfreechart guide, i found method setBaseSectionPaint, but it's didn't work. I used method setSectionPaint in cycle, but it's not right(excess program code). Why setBaseSectionPaint doesn't work?
private JFreeChart createPieChart(PieDataset piedataset){
JFreeChart jfreechart = ChartFactory.createPieChart("Select the desired dictionary:", piedataset,true, true, false);
PiePlot pieplot = (PiePlot) jfreechart.getPlot();
for (int i=0;i<piedataset.getItemCount();i++){ //excess program code
pieplot.setSectionPaint(piedataset.getKey(i),new Color(54, 95, 196));
}
pieplot.setBaseSectionPaint(new Color(54, 95, 196)); //doesn't work
return jfreechart;
}
A:
The PiePlot method drawItem(), among others, invokes lookupSectionPaint(), which explains the algorithm used:
if getSectionPaint() is non-null, return it;
if getSectionPaint(int) is non-null return it;
if getSectionPaint(int) is null but autoPopulate is true, attempt to fetch a new paint from the drawing supplier (Plot.getDrawingSupplier());
if all else fails, return getBaseSectionPaint().
Instead, try this approach, illustrated using org.jfree.chart.demo.PieChartDemo1 after omitting calls to setSectionPaint():
//plot.setSectionPaint(…);
plot.setAutoPopulateSectionPaint(false);
plot.setBaseSectionPaint(Color.blue);
| {
"pile_set_name": "StackExchange"
} |
Q:
How prove this $\{a\}\cdot\{b\}\cdot\{c\}=0$ if $\lfloor na\rfloor+\lfloor nb\rfloor=\lfloor nc\rfloor$
Interesting problem
Let $a,b,c$ be real numbers such that
$$\lfloor na\rfloor+\lfloor nb\rfloor=\lfloor nc\rfloor$$
for all postive integers $n$.
Show that:
$$\{a\}\cdot\{b\}\cdot\{c\}=0$$
where $\{x\}=x-\lfloor x\rfloor$
My partial work: since for any postive intger $n$,have
$$\lfloor na\rfloor+\lfloor nb\rfloor=\lfloor nc\rfloor$$
then we have
$$a+b=c$$
because consider
$$\Longrightarrow \lim_{n\to\infty}\dfrac{\lfloor na\rfloor+\lfloor nb\rfloor}{\lfloor nc\rfloor}=1$$
since
$x-1<\lfloor x\rfloor \le x$,so we have
$$na+nb-2<\lfloor na\rfloor+\lfloor nb\rfloor\le na+nb$$
so
$$1=\lim_{n\to\infty}\dfrac{\lfloor na\rfloor+\lfloor nb\rfloor}{\lfloor nc\rfloor}=\dfrac{a+b}{c}$$
I guess we can use by contradiction prove this. Assume that
$\{a\}\cdot\{b\}\cdot\{c\}\neq0$, then $a,b,c$ all not integer.
A:
For $n=1$ one gets $\lfloor a\rfloor+\lfloor b\rfloor=\lfloor c\rfloor$. Subtracting $n$ times that equation from the given one gives
$$
\lfloor n\{a\}\rfloor+\lfloor n\{b\}\rfloor=\lfloor n\{c\}\rfloor \quad\text{for all $n\in\Bbb N$,}
$$
and together with $\lfloor a\rfloor+\lfloor b\rfloor=\lfloor c\rfloor$ these equations also imply the original ones. But now one only has the fractional parts $a'=\{a\}$, $b'=\{b\}$ and $c'=\{c\}$ in the formulation of the problem.
This means it suffices to show the stated result in the special case $a,b,c\in[0,1)$. I will henceforth assume that.
First I show the conditions imply $a+b=c$. Suppose this equation fails, then choose $n\in\Bbb N$ such that $|a+b-c|\geq\frac2n$. From $|na+nb-nc|\geq2$ it follows that $\lfloor na\rfloor+\lfloor nb\rfloor\neq\lfloor nc\rfloor$, a contradiction.
It remains to prove that for $a,b\in(0,1)$ there always exists some $n\in\Bbb N$ such that $\{na\}+\{nb\}\geq1$, since that means $\lfloor na\rfloor+\lfloor nb\rfloor=nc-(\{na\}+\{nb\})=\lfloor nc\rfloor-1$ contradicting the hypothesis; assuming that, the cases of the reduced problem that satisfy the hypothesis must have $a=0\lor b=0$, which means that one has $\{a\}\cdot\{b\}=0$ in the original problem, stronger than what was needed.
Proving the existence of such an $n$ is a bit technical. If $a+b\geq1$ one can take $n=1$, so assume that $a+b<1$. Choosing $N>0$ with $\frac2N<\min(a,b,1-a-b)$, I claim there exists some $m$ such that $ma$ and $mb$ are both no further than $\frac1N$ from the nearest integer (call the actual differences $\epsilon_a,\epsilon_b$). Then one can take $n=m-1$ because $na\equiv -a+\epsilon_a\pmod1$ implies (due to the smallness of $\epsilon_a$) that $\{na\}=1-a+\epsilon_a$ and similarly $\{nb\}=1-b+\epsilon_b$; combining the two equations gives that $\{na\}+\{nb\}=2-a-b+\epsilon_a+\epsilon_b\geq1+(1-a-b-\frac2N)>1$.
The claim can be proved using the pigeonhole principle: the pairs of remainders modulo$~N$ of $\lfloor mNa\rfloor$ and of $\lfloor mNb\rfloor$ can take only finitely many (namely $N^2$) different values as $m$ varies, so there exist $m_1<m_2$ for which the same pair is obtained; then taking $m=m_2-m_1$, one has that the numbers $ma$ and $mb$ are both at distance less than $\frac1N$ from an integer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Finding the range of a cannonball- proof verification.
I asked such a question before but I do learn best by mistakes and corrections.(I didn't fully understand it yet.) I could really use your verification: A cannonball is being fired with a velocity of 800 $m\over s$ in a straight line with 60 degrees from the ground. What is its range?
Attempt: $v_0=(800\cos 60,800\sin60)$. $a=a_0=-g=(0,-g)$. $v(t)=800\cos60, 800\sin60-gt)$ and $x(t)=(800\cos60t,800\sin60t-{g\over2}t^2)$. The range is the horizontal distance the cannonball travels.(Is it? I am not sure.) In the point it stops, the y-component of the body is 0. By simple computing, $t={400\sqrt{3}\over g}$. The range(?) is, if so, $800\cos60\cdot t=400\cdot {400\sqrt{3}\over g}$.
A:
I'm gonna put in a long answer here since I forgot all of my kinematic equations (sad I know).
From what I remember from taking a course on fundamental physics in college, acceleration is just the second derivative of displacement with respect to time or the first derivative of velocity $\vec a=\frac{d^2 \vec s}{dt^2} = \frac {dv}{dt}$ where $s$ is the displacement.
Thus doing the integrals:
$$ \int \vec a \, dt = \int d \vec v$$
$$ \vec at + \vec v_0 = \vec v(t) \tag{1}\label{1} $$
$$ \int (\vec a t + \vec v_0)\, dt = \int d \vec s$$
$$ \frac {1}{2}\vec at^2 + \vec v_0t + \vec s_0 = \vec s(t) \tag{2}\label{2}$$
Obtaining the needed kinematic equations, we will then solve the problem. Knowing that the cannonball will stop when it lands, we will just have to find the time $t$ when the cannonball is in the ground again, thus we would have to set the displacement in the y-direction $s_y(t)$ to be zero and find the value of time from there. Then using time $t$ and velocity $v_x$, we will plug it in back to $\eqref{2}$ to get the displacement.
$$ 0 = \vec s(t) = v_0yt + \frac{1}{2}\vec a t^2 = t(v_y + \frac{1}{2} \vec a t)$$
We will get two values for $t$ here, one is at the very instant the the cannon fired $t = 0$ and the other one is when the cannonball landed at the ground. Of course we would look for the non-trivial solution so that we would have a good time of solving this.
$$ -v_y = \frac{1}{2} \vec a t $$
$$ \frac {-2 v_y}{\vec a} = t \tag{3}\label{3}$$
We now have the value of $t$ when $s_y(t) = 0$ so we will just have to plug it into equation \eqref{2} for $s_x(t)$. For simplicity's sake, let's call the obtained value of $t$ as $t_1$.
$$\eqref{3} \, \text{to} \, \eqref{2}$$
$$s_x(t_1) = v_0x(t)$$
$$s_x(t_1) = v_0x\left(\frac{-2v_y}{\vec a}\right)$$
So for completeness sake, let's compute for the numerical answer. Letting $a=g=-9.81 \frac {m}{s^2}$, $| \vec v_0| = 800 \frac ms$ and $\vec v_0 = \langle 800\cos60, 800\sin60 \rangle$, we would then compute:
$$ s_x(t_1) = 800 \cos 60 \, \frac {m}{s}\left(\frac {-2}{-9.81 \frac{m}{s^2}}\right)800 \sin60 \, \frac{m}{s}$$
$$ s_x(t_1) = \frac {800}{2} \, \frac{m}{s} \left(\frac {2}{9.81 \frac{m}{s^2}} \right) \frac {800}{2}\sqrt{3} \, \frac{m}{s}$$
$$ s_x(t_1) = 400 \left(\frac {800 \sqrt{3}}{9.81} \right) \, \frac{m}{s} $$
$$ s_x(t_1) = 400 \left(\frac {800 \sqrt{3}}{g} \right) \, \frac{m}{s} $$
So you're just missing a factor of two from your answer, you might have made that mistake in obtaining the value of $t_1$ as shown earlier.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a typographical term for vertically-stacked characters?
I recently discovered this type technique in the July/August edition of Little White Lies Magazine.
Here's an example of the typography:
I wish to know, is there a term for the technique of stacking two characters? This can be seen in the above image in "TRACK" and "RELEASES" with the R/A and E/A respectively?
A:
I am not sure if there is a term of art for the second one (there might be). I would refer to it as "nesting." It is a style that was quite common around 1890-1920, especially Art Nouveau
A:
To @Horatio's answer, there is nesting in there, but there is also some kerning as well. That being said, I'm not sure you will be able to duplicate what you see in that image via CSS. If that graphic isn't handmade, then it is a typeface that was heavily modified to stylize it the way you see there. It certainly goes above and beyond the typical modifications seen in working with type, even for a headline or banner. Sometimes you just have to go with a graphic to achieve a desired effect.
A:
I couldn't immediately find it, but there was an OpenType font release about a year ago by FF or one of the other not-Adobe-not-Linotype-not-ITC foundries that did exactly this kind of thing using a huge number of really quirky ligatures. There isn't really a standard term for this because it's so rare. Horatio suggests "nested", which is as good a term as any. I'd say "stacked" for no special reason other than they are stacked. :-)
(See the other question for more...)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add local filtering option in basic grid using Ext Js 4.2?
I have developed a basic grid using Ext Js 4.2. Here's the output..
Now i wanna add filtering option to the columns in this grid. For example (=, >, <) filtering have to occur.
I have found some source code like which might work but i am struggling where to add those javascript files. Here's my code:
Ext.define("UserListDemo.view.user.UserGrid", {
extend: "Ext.grid.Panel",
alias: "widget.userGrid",
autoHeight:true,
style: 'margin-top: 10px;margin-left: 15px;margin-right: 20px;',
title: '<span style="color: #525252;">User List</span>',
store: 'UserStore',
name: 'userGrid',
id: 'userGrid',
loadMask: true,
syncRowHeight: true,
columns:[
{
text: 'ID',
sortable: true,
dataIndex: 'id',
locked: true,
width: 120
},
{
text: 'Name',
dataIndex: 'name',
locked: true,
width: 350
},
{
text: 'Address',
dataIndex: 'address',
width: 450
},
{
text: 'Contact',
dataIndex: 'contact',
width: 250
},
{
text: 'Telephone',
dataIndex: 'telephone',
width: 200
}
]
});
<html>
<head>
<title>User List</title>
<link href="http://10.11.201.93:81/grid/ext-4.2.1/ext-4.2.1.883/resources/css/ext-all.css"
rel="stylesheet" type="text/css" />
<script src="http://10.11.201.93:81/grid/ext-4.2.1/ext-4.2.1.883/ext-all-debug.js"></script>
<script src="EXTJS_Files/ListApp.js"></script>
<body>
</body>
</html>
Could someone help me with the source code of filtering and how to integrate it with my basic grid as well ?
A:
Finally I have been able to add filtering option into my basic grid. I am sharing the whole process in brief.
Firstly,we should keep in mind that ExtJs is a MVC(MVCS more precisely) kind of framework. So, any kind of feature (grid filtering, chart etc) we have to add we should follow the MVC architecture first. SO, I have to replace the local-filter.js file to the previous UserModel .
Here's is the Model View Controller ( and Store) architecture for ExtJs. I am sharing my whole project's directory.
So, in fine, I place the source code of local-filter.js in UserModel.js replacing the previous source code.
Secondly, You have to just include ListApp.js in the index.php. Then it will implicitly call all the MVC javascript files it needs. Just like that:-
<script src="EXTJS_Files/ListApp.js"></script>
Finally, any json file in the data folder will show the data in the grid which will be shown as the way you filter the date. In this case grid-filter.json has been used. And, you have to set the directory of data in UserMdel.js like that.
So, following these steps and kind of grid with filtering, charts could be developed using ExtJs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I update posts that have been "unduplicated"?
Twice my questions have been voted duplicate and twice I've voted to reopen and been successful in that endeavor. No complaint there, all actions were legitimate IMHO.
In both cases, I added additional text to the posts to justify why they were not duplicate. However, now that they have been reopened, those edits no longer seem relevant. Should I again edit, removing "no dup" justification text or just leave the posts as they are. Questions are:
Can a pilot rated in one category solo in another category without a current flight review?
Is it better to shut down the engine(s) or leave it (them) running when a gear up landing is imminent?
A:
I think it's definitely good that you updated your questions to add more explanation about why they aren't dupes and therefore get them re-opened. That's exactly how the system is supposed to work!
My only 'concern' is an entirely subjective one: although your wording is perfectly clear I personally don't like it. It's a little jarring to read that "this question is marked duplicate" when in fact it isn't any more. My view is that a question should be fully understandable and coherent on its own, without requiring someone to read or even think about previous edits or changes.
Personally, instead of this (from your first question)...
In response to this being marked duplicate:
I was aware that a biennial flight review is valid for any airplane
category [...]
...I'd have written something like this:
I've already seen this related question but I don't believe it's a
duplicate because it doesn't cover the case where a biennial flight review [...]
That provides exactly the same explanation, but it still reads smoothly if the question is later re-opened, and it doesn't have any 'meta-references' to edits or status changes.
A:
Should I again edit, removing "no dup" justification text or just leave the posts as they are
You should definitely leave the posts as they are when reopened.
If you remove the explanation and the reference to the other question, nothing prevents a future user to pass by and vote it to close a duplicate again, as they would not have any idea that the discussion has been settled in the meanwhile.
For this reason I strongly agree with Pondlife's point: you should write the rebuttal to stand on its own, without references to the current status of your question. For example you can look at this question, that was closed as duplicate but has been since reopened.
| {
"pile_set_name": "StackExchange"
} |
Q:
Clarity regarding a proof in approximating even functions
The question asked in (ISI-JRF) exam was:
Let $f$ be a real valued continuous function on $[-1,1]$ such that $f(x)=f(-x)\forall x\in[-1,1]$. Show that $\forall\epsilon\gt0,\ \exists$ a polynomial $p(x)$ with rational coeficients such that $\forall x\in[-1,1]$,$$|f(x)-p(x^2)|\le\epsilon$$.
My proof ran as follows:
By the Weierstraß aproximation theorem, we have that every real valued uniformly continuous function can be approximated by a polynomial with real coefficients, i.e. $\forall\epsilon\gt0,\forall x\in[-1,1],\exists q(x)$(polynomial) such that $$|f(x)-q(x)|\lt\epsilon\cdots(1)$$. Also, by the evenness of the given function, we have:-$$|f(-x)-q(-x)|<\epsilon\implies|f(x)-q(-x)|<\epsilon\cdots(2)$$. Now, adding $(1)+(2)$:- $$|f(x)-q(x)|+|f(x)-q(-x)|<2\epsilon$$. Hence, by triangle inequality, $$|q(x)-q(-x)|\lt2\epsilon$$, i.e., the polynomial is also even. Hence, $\exists$ a polynomial $p(x)$ such that $p(x^2)=q(x)$. Now, since rational numbers are dense in real numbers, therefore, we obtain the desired result.
I think the above proof is correct. If the proof is incorrect, please provide hints regarding right proof. Thanks beforehand.
A:
You have that,
as angryavian commented,
$q$ is almost even.
For any function $f$,
$g(x)
=\frac12(f(x)+f(-x))
$
is exactly even.
So,
consider
$r(x)
=\frac12(q(x)+q(-x))
$.
Then
$r(x)$ is exactly even
and
$|r(x)-q(x)|
=|\frac12(q(x)-q(-x))|
$
is also small,
so
$|r(x)-f(x)|$
is also small.
Now use $r(x)$
as a polynomial with
only terms with
even exponents.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best way to move JFrame to 2nd display in Windows 10
I'm trying to move my jframe to second display automatically in windows 10 but its not working, I'm using JDK8, and video drivers are upto date below is my code:
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DualMonitor {
public static void main(String... args) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, "Found : " + gs.length, "screen detected ?",
javax.swing.JOptionPane.DEFAULT_OPTION);
for (int j = 0; j < gs.length; j++) {
GraphicsDevice gd = gs[j];
JFrame frame = new JFrame(gd.getDefaultConfiguration());
frame.setTitle("I'm on monitor #" + j);
frame.setSize(400, 200);
frame.add(new JLabel("hello world"));
frame.setVisible(true);
}
}
}
A:
Issue is resolved by using setLocationRelativeTo, setUndecorated and setExtendedState(JFrame.MAXIMIZED_BOTH) check below:
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DualMonitor {
public static void main(String... args) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, "Found : " + gs.length, "screen detected ?",
javax.swing.JOptionPane.DEFAULT_OPTION);
for (int j = 0; j < gs.length; j++) {
GraphicsDevice gd = gs[j];
JFrame dualview = new JFrame(gd.getDefaultConfiguration());
JFrame frame = new JFrame();
frame.setLocationRelativeTo(dualview);
dualview.dispose();
frame.setUndecorated(true);
frame.setTitle("I'm on monitor #" + j);
frame.setSize(400, 200);
frame.add(new JLabel("hello world"));
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Using identities from Euclid's algorithm to solve problems
I have been given the following problems
(a) Use the $GCD$ algorithm to compute the greatest common divisor of $546$ and $416$.
(b) Use your working for the previous part to express $\frac{416}{-546}$ as a rational ${m \over n}$ where $n\geq 1$ and $\gcd(m,n)=1$.
I am able to do part (a) and was left with the following working
$\gcd(416,546)$
$\rightarrow 546 = 1 * 416 + 130$
$\gcd(130,416)$
$\rightarrow 416 = 130 * 3 + 26$
$\gcd(26,130)$
$\rightarrow 130 = 5 * 26 + 0$
$\gcd(0, 26)$
therefore $\gcd(416,546)=26$
Then with part (a), I found that because
$416 = 16 * 26$ and $546 = 21 * 26$
That ${16 \over -21}$ is the answer, this is wrong, and I'm struggling to see what I need to do to begin on this problem
A:
If $gcd(m,n)=1$ then $m/n$ is a fraction reduced to its lowest terms, so you've actually used that fact.
And as I said in the comments, the other condition in part b) is that you have to ensure that $n≥1$, which is why your original answer was wrong.
| {
"pile_set_name": "StackExchange"
} |
Q:
Same low with different hole cards - who wins?
Board: A 4 5 7 J
Two players declare a low.
Player A: 3 4 x x
Player B: A 3 x x
Both players have the same low hand: A 3 4 5 7
Is this a tie or does Player B win with lower cards in his hand?
A:
It's a tie. Win/loss is always dependent on 5 cards. The only times differences in hand cards matter is when determining who gets the extra chip(s) in a split pot. (Though some casinos go by position instead of hand cards for this.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Does downvoting a question help "hide" it?
Possible Duplicate:
How many downvotes to push an active question off the “active” list?
The question Find and replace first space in a string, while very much a question where the OP apparently hasn't tried Googling first, doesn't seem to fit any of the close reasons, so I downvoted it instead.
Does downvoting a question help "hide" it in any way? I checked the privileges page, and grepped the FAQ, and neither mention downvoting "hiding" a question. I also couldn't find anything searching for "[faq] voting" either.
A:
That depends on whether you have access to the 10k tools...:
No freehand circles I'm afraid, but there you see a review of questions with high down votes over varying period. This is available to all 10k+ users, so if a question has received unfair treatment from the community, we are able to edit/vote to fix it.
As I understand it, on the home page of main sites, -4 is the lowest a question may score before it disappears from view. However, it still appears in the question list. Any quality flags it triggers will appear in review; also, if it attracts close votes it will appear in review, where it must be reviewed by 2 (?) users before it is deemed "reviewed".
In short, there are many ways in which downvoted content is exposed and can be reviewed. If you have the 10k tools, or access to review, you have an advantage.
| {
"pile_set_name": "StackExchange"
} |
Q:
Boolean returns false first time in activity
I have a method that returns true if a child is present in the database and false if not. It looks like this:
boolean subscriber;
public boolean checkChatRoomMembership(String chatRoomUid) {
mChatRoomMembers.child(chatRoomUid).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(mAuth.getUid())) {
subscriber = true;
} else {
subscriber = false;
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
return subscriber;
}
Even though the the node is present in the database it returns false the first time the method is ran. The following times it returns true as it should. It is always the first time the activity is started that it returns false. Any ideas why?
A:
When the function is called the first time, callbacks inside the function has not been called. Yet data is not retrieved and your function return default value of "subscriber" variable. After the first call to this function "subscriber" value updates when the callback is called.
public void checkChatRoomMembership(String chatRoomUid) {
mChatRoomMembers.child(chatRoomUid).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(mAuth.getUid())) {
// true, do you work here
} else {
// false, do you work here
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Hope this will help you.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to put words into a variables and check if it matches the data in database
I am using MSSQL and C# to write a search engine. I got a bunch of stop words in the database. In my default.aspx page, I got a textbox and a search button. Users can type in a whole sentence into the textbox.
I wrote the code for searching a single keyword but not a whole sentence. This is the function in default.aspx.cs
private void ImageSearch()
{
if (txtSearch.Text.Trim().Equals(""))
{
//when types nothing
txtSearch.Focus();
Warning.Text = "Please enter the keyword to search";
//display message
return;
}
else
{
int check = Process.CheckStopWord(txtSearch.Text.Trim());
//check if the keyword is stop word
if (check == 0)
{
txtSearch.Focus();
Warning.Text = "No stop word found";
}
else
{
txtSearch.Focus();
Warning.Text = "Found Stop word";
}
}
}
and for the checkstopword function
public static int CheckStopWord(string keyword)
{
string check = "0";
string query = "SELECT COUNT (stopword) FROM stopwordtb WHERE [stopword] like '" + keyword + "'";
//count how many stop word matches the keyword entered, return a string of a number
accessDB dbaccess = new accessDB();
DataSet ds = dbaccess.queryData(query);
DataTable dt = ds.Tables[0];
if (dt.Rows[0][0].ToString() == check)
{
return 0;
//keyword != stop word in stopwordtb
// begin search in image database - not implemented yet
}
else
{
return 1;
//keyword = stop word in stopwordtb
}
}
my problem is, what if the user type in a whole sentence?
For example, if he types in " The tree" in the textbox, but "The" is a stop word, so I will just ignore the "the" and just search the image database for "tree".
How can I put the sentence into variables and search each of them individually? or are there any faster way?
Hope somebody can give me some help. Thanks
A:
You need something like string[] words = sentence.Split(' '); then check each entry in the words array.
A:
Before you search in the database, you may first split the sentence, and then check each word is a stop word using a loop (ex: while-loop),
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python multiplication table, seperte with strings
I want to create a function that takes 2 parameter, and prints the multiplication table for this number in a nice format where rows are separated by lines. This is the target:
target design
I have tried, but have no idea where to integrate the "--------" string. Any ideas?
def multi_table(x,y):
for row in range(1, x+1):
for col in range(1, y+1):
num = row * col
if num < 10: blank = ' '
else:
if num < 100: blank = ' '
print(blank, num, end = '')
print()
multi_table(4,5)
A:
You need to add the print statement between the row and column loop. You also need to ensure that you end the print statement with a new line character \n. Refer below.
def multi_table(x,y):
for row in range(1, x+1):
print("---------------------\n")
for col in range(1, y+1):
num = row * col
if num < 10: blank = ' '
else:
if num < 100: blank = ' '
print(blank, num, end = '')
print()
multi_table(4,5)
| {
"pile_set_name": "StackExchange"
} |
Q:
Can the data transfer object`s data match the UI needs
The data transfer object holds data from multiple business objects sent to the client.
But should/could this data and its structure be extra setup for the client to fit its binding needs?
Or should I extra create a ViewModel for this?
Its a small application so I am hesitating about too much overarchitecting and the dto`s would be 90% the same as the viewmodels...
The DTO`s would be transfered from a restful server to a javascript client not more.
A:
I think the thing to consider is what differences exist between the VM and DTO. A while back, I was attempting to create C# view models which implemented, derived from, or contained the DTO contract plus all the view centric stuff such as select list options and filter properties. I found this to be cumbersome, fragile and WET (as opposed to DRY ;).
I've since moved to a pattern of defining my view models in JavaScript and allowing the DTO objects to contain only the properties necessary to satisfy the contract expectations of the service layer. I pull data down using ajax. The data is typically passed into the view in the format it was received from the service. I then update my data-bound, observable knockout view models. So far, this pattern has been really productive for me.
With regard to input validation, so long as we're talking about validation attributes, I think it's perfectly fine that you have validation attributes defined on your DTO. After all, your API controller has a ModelState for a reason. Unfortunately, there's not a really good method to translate that validation into your client-bound views. As such, I've been leaning on knockout validation more than MVC's validation. I'm holding on to hope, however, that there is a better solution validation solution out there!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to parse a tab-separated line of text in Ruby?
I find Ruby's each function a bit confusing. If I have a line of text, an each loop will give me every space-delimited word rather than each individual character.
So what's the best way of retrieving sections of the string which are delimited by a tab character. At the moment I have:
line.split.each do |word|
...
end
but that is not quite correct.
A:
I'm not sure I quite understand your question, but if you want to split the lines on tab characters, you can specify that as an argument to split:
line.split("\t").each ...
or you can specify it as a regular expression:
line.split(/\t/).each ...
Each basically just iterates through all the items in an array, and split produces an array from a string.
| {
"pile_set_name": "StackExchange"
} |
Q:
How about including a small amount of example code in a large framework?
I am about to upload a fairly large project of mine, a very flexible component-entity-system. More precisely it's a framework for a CES. It consists of 22 files, ~1000 lines of code and 20000 characters.
My problem is that in order to demonstrate what the framework does, I have 2 base component types (input, graphics) and 2 types of entities included in the framework. This is basically example code, unlike the framework itself. The base components have empty implementation too. However if I omitted these "examples" the usage and usefulness of the framework would be rather inconvenient to figure out. So I have empty implementation of base components and components specific to the particular entities (deriving from base components), because these classes' pure existence gives meaning to the framework's capabilities. Although having this kind of empty implementation is pretty much like having pseudo-code (even if everything compiles) and these tiny segments of code are not open to being reviewed therefore.
As an example here is an example component of an entity, where InputComp<> is the abstract base class for all InputComp< 'entity name' > classes.
template<>
class Comp<CompBase::INPUT, void> : public CompBase
{
// Abstract Input component implementation.
};
template<typename Ent_t = void>
using InputComp = Comp<CompBase::INPUT, Ent_t>;
// in another part of the code
template<>
class InputComp<Monkey> : public InputComp<>
{
// Monkey specific Input component implementation.
};
So is it okay to have a small amount of example-like code breathing life into a framework, included in the framework, given proper labeling of these segments.
A:
Yes, example code as a small part of a question, clearly labeled as example not for review, is perfectly fine, and even helpful.
That is assuming the rest of the question is real, fully working code, as per our on-topic rules in the help center.
And as @Mast pointed out, keep in mind that it's difficult to get good answers when you post a lot of code. You might want to split to multiple questions, highlighting different parts. That's not a rule, just a tip, for your consideration, to make the most out of your post.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fill an array with pairs of numbers in C
I have a little programming project in C. I am really new to this topic so I appreciate every little help. The object is: I need to fill an array with pairs of numbers until the user types in -1. Then the user gives a command (Bigger or smaller) in the console. If the user types in smaller, then the program has to list every pair, that's first number is smaller than the second one.
I could write it until this:
#include <stdio.h>
#define Max_Number 20
struct numberPairs {
int firstNum, secondNum;
};
struct numberPairs input(){
struct numberPairs firstInput;
printf("Please give me the first number! \n");
scanf("%d", &firstInput.firstNum);
printf("Please give me the second number! \n");
scanf("%d", &firstInput.secondNum);
return firstInput;
}
struct numberPairs ArrayInput (struct numberPairs x){
struct numberPairs array[Max_Number], pairs;
int index=0;
do{
pairs=input();
array[index]=pairs;
index++;
if (pairs.firstNum == -1 || pairs.secondNum == -1){
break;
}
}while(index<5 );
}
int main (){
struct numberPairs t;
ArrayInput(t);
}
Basically I don't know how to do it any further.
A:
First, make array[Max_Number] a global array as now it is an array that is local to the ArrayInput function and is gone when the function returns. By making it global, it will stay and can be used by other functions. The function now is of type void ArrayInput(void).
After calling ArrayInput in main you now have the array. Now ask the user for larger or smaller and then go through the array to list the elements meeting the user's requirement. You can do that as a new function that uses the global array.
| {
"pile_set_name": "StackExchange"
} |
Q:
Puppet removes Foreman VirtualHosts when installing OpenStack
My introduction to Puppet and Foreman has been very painful, but I know there's a big community around it, so I'm hoping that someone can set me straight here.
I set up Foreman and Puppet using the Foreman-Installer and it went great. I had Foreman up and running and it worked great! However, I added the OpenStack controller role to the machine, it wiped out the Apache vhosts for Foreman. I've scoured Google and Github for copies of the vhost files, but with no luck.
So the main questions here:
1) How do I locate/generate the Foreman vhosts for Apache?
2) How do I prevent Puppet from removing them again?
Thanks in advance all you Puppet Masters!
A:
To prevent Puppet from blasting your Apache config, start managing that config through Puppet.
I'm not sure how your OpenStack controller role works, but it likely employs the puppetlabs-apache module, which will purge unmanaged configuration. You should use this module to configure the Foreman vhost on the machine.
As for getting it back - Puppet should have stored the contents of deleted files in the clientbucket. Check the logs on that machine. There should be md5 sums for all removed files. Use those to retrieve the contents, either through the filebucket tool, or by manually trudging /var/lib/puppet/clientbucket (or whatever puppet agent --configprint clientbucketdir yields).
| {
"pile_set_name": "StackExchange"
} |
Q:
Extracting Json Data from PHP log file
I am newbie to php,
Here is my json file ,
{"hint_data":{"locations":["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB","bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],"checksum":326195011},"route_name":["",""],"via_indices":[0,15],"via_points":[[25.299982,55.376873],[25.29874,55.369179]],"found_alternative":false,"route_summary":{"end_point":"","start_point":"","total_time":101,"total_distance":871},"route_geometry":"{_ego@m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli@hsEfFzn@QlTgNhwCs@fKwBjF","status_message":"Found route between points","status":0}
I need to extract the total_time only from the json and print it to a csv file,could someone please help me in that?
A:
Using json_decode you can get the total time from your json.
Using the json_decode you can get the associative array and using the indices you can access the value of total time as shown below.
Check online
$json = '{"hint_data":{"locations":["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB","bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],"checksum":326195011},"route_name":["",""],"via_indices":[0,15],"via_points":[[25.299982,55.376873],[25.29874,55.369179]],"found_alternative":false,"route_summary":{"end_point":"","start_point":"","total_time":101,"total_distance":871},"route_geometry":"{_ego@m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli@hsEfFzn@QlTgNhwCs@fKwBjF","status_message":"Found route between points","status":0}';
$assoc = true;
$result = json_decode ($json, $assoc);
echo $result['route_summary']['total_time']; //101
| {
"pile_set_name": "StackExchange"
} |
Q:
Android - Opening phone deletes app state
I'm writing an android application that maintains a lot of "state" data...some of it I can save in the form of onSaveInstanceState but some of it is just to complex to save in memory.
My problem is that sliding the phone open destroys/recreates the app, and I lose all my application state in the process. The same thing happens with the "back" button, but I overloaded that function on my way. Is there any way to overload the phone opening to prevent it from happening?
Thanks in advance.
A:
I think the smarter thing to do is to correctly handle the screen-orientation change event and be able to programmatically save and reload your data, rather than trying to fight the phone and the way the OS is intended to work. There is an article in the dev guide titled Faster Screen Orientation Change which you may find useful.
In addition the Shelves sample app deals with this event well, and has a few good examples about cancelling and restoring async tasks when the orientation changes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do questions on the Game Center belong on here or Gaming.SE?
There is no tag for the iOS Game Center.
Should any questions on it be asked here, or on https://gaming.stackexchange.com/ or elsewhere?
Or should cross-posting be allowed in this instance?
A:
Game Center would be on-topic here since it is Apple software.
However, if you're asking about programming or developing for/with Game Center, that would be off-topic since this site is not about development. That kind of a question should go on Stack Overflow.
If you've got a question about Game Center that doesn't involve development/programming, go ahead and ask it here. I can easily make you a [game-center] tag.
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift Cocoa buttons not in place
I'm new doing Cocoa Touch but I worked whit java swing, I made what I suppose draw to buttons on the screen, one on the left (green) and other on the right (blue), but I only see the blue one the other is missing. It's a class of a view with two buttons on it.
import UIKit
class MouseClick: UIView {
//MARK: Atributes
var clicks = [UIButton]()
//MARK: Initializer
required init?(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
//let bounds = UIScreen.mainScreen().bounds
let button = UIButton()
// x: start of x in frame, y: start of y in frame width:half screen, height:full screen
let leftButtonFrame = CGRect(x: frame.origin.x, y:frame.origin.y, width: frame.size.width/2.0, height:frame.size.height)
// x: start of x in frame plus the half, y: start of y in frame width:half screen, height:full screen
let rigthButtonFrame = CGRect(x: frame.origin.x + frame.size.width/2.0, y: frame.origin.y, width: frame.size.width/2.0, height: frame.size.height)
//test action (only prints)
button.addTarget(self, action: "clickAction:", forControlEvents: .TouchDown)
clicks = [button, button]
clicks[0].frame = leftButtonFrame
clicks[1].frame = rigthButtonFrame
clicks[0].backgroundColor = UIColor.greenColor()
clicks[1].backgroundColor = UIColor.blueColor()
addSubview(clicks[0])
addSubview(clicks[1])
}
override func layoutSubviews() {
// Set butons(clicks) size, width:half screen, height:full screen
let buttonSize = Int(frame.size.height)
var buttonFrame = CGRect(x: 0.0, y: 0.0, width: frame.size.width/2.0, height: CGFloat(buttonSize))
// set x position for every button in clixk
for (index, button) in clicks.enumerate() {
buttonFrame.origin.x = CGFloat(index) * frame.size.width/2.0
button.frame = buttonFrame
}
}
override func intrinsicContentSize() -> CGSize {
let heigth = Int(frame.size.height)
let width = Int(frame.size.width)
return CGSize(width: width, height: heigth)
}
//MARK: Clicks actions
func clickAction(button: UIButton)
{
var n = clicks.indexOf(button)!
if n == 0
{
print("leftie")
} else
{
print("rightie")
}
}
}
the resulting image here,
]1
A:
The problem is that you initialize only one button. The 'clicks' array contains two references pointing to the same Button. This is why you only see one on Screen.
let button = UIButton()
let button2 = UIButton()
.
.
.
clicks = [button, button2]
Now you have two buttons.
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamical overriding
I want to dynamically instantiate a QWidget and bind its "Pressed" event, either with a Qt signal or by overriding a function.
However I'm only allowed to create one new .cpp file.
I don't know how to override a C++ function dynamically, or how to change a virtual function into a Qt signal.
Is what is represented in the picture above achievable ?
A:
The Widgets Tutorial of the Qt docs is a nice starting point.
Under Qt Widgets Examples you can find the Calculator Example, which should contain all of what you want to do.
Take the code, strip it down to what you need, use and try to understand it.
Or maybe have a look at the Getting Started section.
| {
"pile_set_name": "StackExchange"
} |
Q:
flake8 and "old style class declaration"
I use flake8 to check formatting of my python3 scripts. When I declare classes like this...
class MyClass:
...I get a warning "H238 -- old style class declaration, use new style (inherit from object)".
However, the documentation clearly has declarations just like this: https://docs.python.org/3/tutorial/classes.html#class-definition-syntax
I think that inheriting from object looks unnecessarily cluttered. Is it functionally different? The documentation doesn't say anything about inheriting from object.
Is this a bug with flake8, or am I just missing something obvious?
A:
The documentation says:
It is very important to install Flake8 on the correct version of Python for your needs. If you want Flake8 to properly parse new language features in Python 3.5 (for example), you need it to be installed on 3.5 for Flake8 to understand those features. In many ways, Flake8 is tied to the version of Python on which it runs.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can you use glVertexAttribPointer to assign a smaller vector to a larger one?
From section 5.8 of The OpenGL® ES Shading Language (v1.00, r17) [PDF] (emphasis mine):
The assignment operator stores the value of the rvalue-expression into the l-value and returns an r-value with the type and precision of the lvalue-expression. The lvalue-expression and rvalue-expression must have the same type. All desired type-conversions must be specified explicitly via a constructor.
So it sounds like doing something like this would not be legal:
vec3 my_vec3 = vec3(1, 2, 3);
vec4 my_vec4 = my_vec3;
And to make it legal the second line would have to be something like:
vec4 my_vec4 = vec4(my_vec3, 1); // add 4th component
I assumed that glVertexAttribPointer had similar requirements. That is, if you were assigning to a vec4 that the size parameter would have to be equal to 4.
Then I came across the GLES20TriangleRenderer sample for Android. Some relevant snippets:
attribute vec4 aPosition;
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices);
So aPosition is a vec4, but the call to glVertexAttribPointer that's used to set it has a size of 3. Is this code correct, is GLES20TriangleRenderer relying on unspecified behavior, or is there something else I'm missing?
A:
The size of the attribute data passed to the shader does not have to match the size of the attribute in that shader. You can pass 2 values (from glVertexAttribPointer) to an attribute defined as a vec4; the leftover two values are zero, except for the W component which is 1. And similarly, you can pass 4 values to a vec2 attribute; the extra values are discarded.
So you can mix and match vertex attributes with uploaded values all you want.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sorting multiple subarrays based on a total count from all sub arrays
I have some data which looks like this (reduced)
Array
(
[datasets] => Array
(
[0] => Array
(
[label] => NEW
[backgroundColor] => #37fdfd
[data] => Array
(
[0] => 0
[1] => 0
[2] => 5
[3] => 0
)
)
[1] => Array
(
[label] => Grade A
[backgroundColor] => #76ef76
[data] => Array
(
[0] => 8
[1] => 12
[2] => 11
[3] => 0
)
)
[2] => Array
(
[label] => Grade B
[backgroundColor] => #f9f96d
[data] => Array
(
[0] => 1
[1] => 6
[2] => 5
[3] => 3
)
)
[3] => Array
(
[label] => Grade C
[backgroundColor] => #f3ca36
[data] => Array
(
[0] => 3
[1] => 0
[2] => 1
[3] => 4
)
)
[4] => Array
(
[label] => Grade D
[backgroundColor] => #f3ca36
[data] => Array
(
[0] => 3
[1] => 0
[2] => 1
[3] => 0
)
)
)
[labels] => Array
(
[0] => User 0
[1] => User 1
[2] => User 2
[3] => User 3
)
)
Here is a JSON string of the data (not reduced, numbers may differ slightly)
{"datasets":[{"label":"NEW","backgroundColor":"#37fdfd","data":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},{"label":"Grade A","backgroundColor":"#76ef76","data":[9,14,12,0,4,17,13,0,10,0,18,18,12,13,13,4]},{"label":"Grade B","backgroundColor":"#f9f96d","data":[1,6,5,0,6,5,2,0,1,0,2,1,4,3,1,15]},{"label":"Grade C","backgroundColor":"#f3ca36","data":[3,0,1,0,2,0,0,0,0,0,1,1,0,0,0,0]},{"label":"Grade C","backgroundColor":"#f3ca36","data":[3,0,1,0,2,0,0,0,0,0,1,1,0,0,0,0]}],"labels":["User 0","User 1","User 2","User 3","User 4","User 5","User 6","User 7","User 8","User 9","User 10","User 11","User 12","User 13","User 14","User 15"]}
Each dataset has an array of data which has keys that directly relates to a key in the labels array. This is currently sorted in alphabetical order by the label.
This data structure is the structure required for Chart.js, which I am using to display a stacked bar chart on my webpage.
Essentially what I need to accomplish is to sort the data array for every user in the labels array based on the sum of each data set for that user. I also need to sort the labels array to be in the same order.
My original idea on how to achieve this is to create a temporary array, loop through all the data sets and add them to this temporary array in the order necessary, but I got stuck after calculating the total for each user. Here is my attempt:
$return = [];
foreach($calculated['labels'] as $key => &$name) {
$total = 0;
foreach($calculated['datasets'] as $dataset) {
$total += $dataset['data'][$key];
}
echo "$name - $total<br>";
}
How can I sort my data and labels in descending order based on the total for each user from all datasets.
Here is my expected output for the reduced data above
Array
(
[datasets] => Array
(
[0] => Array
(
[label] => NEW
[backgroundColor] => #37fdfd
[data] => Array
(
[2] => 5
[1] => 0
[0] => 0
[3] => 0
)
)
[1] => Array
(
[label] => Grade A
[backgroundColor] => #76ef76
[data] => Array
(
[2] => 11
[1] => 12
[0] => 8
[3] => 0
)
)
[2] => Array
(
[label] => Grade B
[backgroundColor] => #f9f96d
[data] => Array
(
[2] => 5
[1] => 6
[0] => 1
[3] => 3
)
)
[3] => Array
(
[label] => Grade C
[backgroundColor] => #f3ca36
[data] => Array
(
[2] => 1
[1] => 0
[0] => 3
[3] => 4
)
)
[4] => Array
(
[label] => Grade D
[backgroundColor] => #f3ca36
[data] => Array
(
[2] => 1
[1] => 0
[0] => 3
[3] => 0
)
)
)
[labels] => Array
(
[2] => User 2 //23 total across all data sets
[1] => User 1 //18 total across all data sets
[0] => User 0 //15 total across all data sets
[3] => User 3 //7 total across all data sets
)
)
The key in the labels array acts as a unique identifier for each user in each dataset data array.
Notice how each set of data inside of each dataset is in the same order, as is the labels array. Each set should be ordered by the total amount from all sets for each user, not necessarily the highest number in each dataset.
For clarification, each set of data in each dataset contains a list of values, the key for each value is directly related to the key for each user in the labels array. So in my example, we have User 0 who has the key "0". This user has a total of 23 from adding up the values from each dataset with the key "0".
A:
Complete solution:
// get array
$a = json_decode('{"datasets":[{"label":"NEW","backgroundColor":"#37fdfd","data":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},{"label":"Grade A","backgroundColor":"#76ef76","data":[9,14,12,0,4,17,13,0,10,0,18,18,12,13,13,4]},{"label":"Grade B","backgroundColor":"#f9f96d","data":[1,6,5,0,6,5,2,0,1,0,2,1,4,3,1,15]},{"label":"Grade C","backgroundColor":"#f3ca36","data":[3,0,1,0,2,0,0,0,0,0,1,1,0,0,0,0]},{"label":"Grade C","backgroundColor":"#f3ca36","data":[3,0,1,0,2,0,0,0,0,0,1,1,0,0,0,0]}],"labels":["User 0","User 1","User 2","User 3","User 4","User 5","User 6","User 7","User 8","User 9","User 10","User 11","User 12","User 13","User 14","User 15"]}', true);
// get array of arrays with `data` key from each data set
$users = array_column($a['datasets'], 'data');
// tricky code to sum arrays
$sums = array_map('array_sum', array_map(null, ...$users));
// sort array with keeping keys
arsort($sums);
// we need flip so as `array_replace` will work as expected
$keys = array_flip(array_keys($sums));
// "sorting" `data` subarrays
foreach ($a['datasets'] as &$item) {
$item['data'] = array_replace($keys, $item['data']);
}
// "sorting" `labels` subarray
$a['labels'] = array_replace($keys, $a['labels']);
// see the result
print_r($a);
Fiddle here https://3v4l.org/a7rPL
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting unique_constraint Ecto
I have have a User model with an email field. Now I would like to make it unique, so, as per documentation, I need to apply:
cast(user, params, ~w(email), ~w())
|> unique_constraint(:email)
Also, I should define the unique index in a migration:
create unique_index(:users, [:email])
The problem is that when I tried to define this in a migration while adding some more fields it didn't work and now I'm trying to just define a migration with this create unique_index(:users, [:email]) and it's creating an error:
[info] create index users_email_index
** (Postgrex.Error) ERROR (unique_violation): could not create unique index "users_email_index"
What am I doing wrong?
A:
This can happen when the unique constraint is already violated in your table.
Please check that you do not already have duplicate email addresses in your users table.
You can run mix do ecto.drop, ecto.create, ecto.migrate to delete and recreate the database and tables.
| {
"pile_set_name": "StackExchange"
} |
Q:
Importing Core Data to existing project fails
I have a workspace and I'm trying to add Core Data to it. I went to the project I want to add Core Data to, selected the Target, hit the + sign under Link Wit Binary Files and added the Core Data framework. That part works fine. I can build and run. When I try the next and using this line:
#import <CoreData/CoreData.h>
I get build errors. These build errors look like:
"ARC Semantic Issue"
Pointer to non-const type 'id' with no explicit ownership
These errors are present in
NSEntityDescription.h
NSManagedObjectModel.h
NSMnagedObject.h
NSManagedObjectContext.h
NSPersistentStore.h
Does anyone know why I'm not able to import Core Data to an existing iOS project? Thanks in advance!
A:
It should be as simple as adding CoreData.framework to your target:
Click the plus button (+) under Linked Frameworks and Libraries
Then in your Prefix file (Tabs-Prefix.pch in this case) in the #ifdef __OBJC__ declaration:
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#impport <CoreData/CoreData.h> //Added core data here
#endif
If this does not work, perhaps you have an older version of Xcode installed and the paths are messed up. It could be trying to import an older framework.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I mock a method making an AJAX call?
I am trying to write some tests for my Angular application and I would like to mock a method so that I do not make an actual call to the server.
Here is my method inside of my grid.service.ts:
loadAccountListPromise(id: string) {
let promise = new Promise((resolve, reject) => {
this.http.get(`${this.baseUrl}`)
.toPromise()
.then(
(data) => {
this.results = this.formatData(data.json());
resolve(this.results);
},
(msg) => {
reject(msg);
}
);
});
return promise;
}
So far I have tried writing something like this following the official angular test guide. In my grid.service.spec.ts I have:
it('loadAcountListPromise should return Promise', () => {
let someHttp;
spyOn(myInnergridService, 'loadAccountListPromise').and.callThrough();
myInnergridService.loadAccountListPromise(someHttp).then(
( response ) => { expect( response ).toBe( jasmine.any(Promise) );
});
});
Here I am spying on the method but by calling .callThough() I am using the actual implementation and thus making a real AJAX call to the server. I want to avoid this and fake the GET request for testing purposes. How do I do this?
A:
First, the testbed :
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
YourService,
// ... Other services
{ provide: XHRBackend, useClass: MockBackend }
]
});
});
then, in every test (or in a beforeEach) :
it('testing http calls ...', inject([YourService, XHRBackend], (service: YourService, http: MockBackend) => {
let cnt: MockConnection;
let response = { contenu: 'anything you want here' };
http.connections.subscribe((connection: MockConnection) => {
cnt = connection;
// Response (CHOOSE ONE)
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(response)
})));
// Error (CHOOSE ONE)
connection.mockError(new Error('error'));
});
let goodCall = (method, url) => {
expect(cnt.request.method).toBe(method);
expect(cnt.request.url.endsWith(url)).toBe(true);
};
service.method().subscribe(res => goodCall(RequestMethod.Get, 'params/search'));
}));
Feel free to ask if you don't understand !
| {
"pile_set_name": "StackExchange"
} |
Q:
-moz-linear-gradient breaking when -webkit-linear-gradient is added on JQuery Slider
TL;DR -webkit-linear-gradient is breaking -moz-linear-gradient
So hear's the conundrum, I'm using the Jquery Slider plugin with two handles on it and I have a gradient as the background color to give the outside ranges some color. What I'm trying to do is update the percentages on the gradients when the slider moves. It works in Chrome / Safari, but not in Firefox when both the -moz and -webkit tags are used. The value is being pulled from the position of the first slider.
When I only have the -moz-linear-gradient tag it works but as soon as I add the -webkit-linear-gradient tag it breaks for Firefox.
Here's the code
HTML:
<div id="traffic-allocation">
<h4 id="traffic-allocation-hed">Traffic Allocation <small>Change by dragging handles right or left and applying changes</small></h4>
<div class="slideContainer">
<div id="slider-direct" class="slider"></div>
</div>
</div>
<div class="labelBox">
<div class="control-box" id="control-box-direct">
<input id="control-direct" type="text" value="35%" class="allocation-control" />
<div class='allocation-control-wrapper'>
<h4 class="variantLabel mycontrol-label" id="mycontrol-label-direct">Control: </h4>
</div>
</div>
</div>
JavaScript:
$(function() {
$( '.slider' ).slider({
range: true,
values: [35, 70],
min: 0,
max: 100,
step: 5,
slide: function( e, ui ) {
//Derive calling (class selector) element's ID and set the IDs for its "companion" value displays:
theSegment = e.target.id.slice(7);
theControl = '#control-' + theSegment;
$( theControl ).val( ui.values[ 0 ] + '%' );
var slidercolor = $('#control-direct').val();
$('.ui-slider-horizontal').css({
background: '#0e76bc', /* Old browsers */
background: 'linear-gradient(to right, #0e76bc '+slidercolor+',#e78f08 '+slidercolor+')' ,/* W3C */
background: '-moz-linear-gradient(left, #0e76bc '+slidercolor+', #e78f08 '+slidercolor+')', /* FF3.6+ */
background: '-webkit-linear-gradient(left, #0e76bc '+slidercolor+',#e78f08 '+slidercolor+')' /* Chrome10+,Safari5.1+ */
})
}
});
CSS:
h1 {
font-family: Helvetica, Arial;
font-weight: bold;
font-size: 18px;
}
body, p{
font-family: Helvetica, Arial;
}
.ui-slider-horizontal{
background: '#0e76bc', /* Old browsers */
background: linear-gradient(to right, #0e76bc 50%,#e78f08 50%); /* W3C *
background: -moz-linear-gradient(left, #0e76bc 50%, #e78f08 50%); /* FF3.6+ */
background: -webkit-linear-gradient(left, #0e76bc 50%,#e78f08 50%); /* Chrome10+,Safari5.1+ */
}
.ui-widget-header {
background: none repeat scroll 0 0 #292668;
border: 1px solid #CCCCCC;
color: #292668;
font-weight: bold;
}
Here's a link to see what's going on and the css cause there's a lot of it :). (open in chrome/safari to see what it's supposed to do and firefox to see it broken)
http://jsfiddle.net/DrewLandgrave/bep9A/
Thank you in advance :)
A:
I modified the fiddle. Instead of multiple background properties, you need to have multiple css calls. Try this: http://jsfiddle.net/bep9A/1/
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle SQL and PL/SQL context switches
I have a code in oracle pl sql, want to really want to understand how much context switching is there
If x=0 then
curserx= select a from mytable1;
Else
curserx=select a from mytable1 where id=:x;
End;
Loop
Fetch on cursorx
Select c from mytable2 where a=curserx.a;
End loop;
This is just a sample code so please pardon any text casing and logic error.
A:
I converted your pseudo code into PL/SQL and include comments indicating where I believe you will have a context switch from the PL/SQL engine to the SQL engine.
Note that if you are querying a non-trivial number of rows, you could use FETCH BULK COLLECT INTO and retrieve multiple rows with each fetch, greatly reducing context switches.
DECLARE
l_x_value INTEGER;
l_cursor SYS_REFCURSOR;
l_fetched mytble1.a%TYPE;
BEGIN
/* context switch to open */
IF x = 0
THEN
OPEN l_cursor FOR SELECT a FROM mytable1;
ELSE
OPEN l_cursor FOR
SELECT a
FROM mytable1
WHERE id = l_x_value;
END IF;
LOOP
/* context switch per fetch */
FETCH l_cursor INTO l_fetched;
EXIT WHEN l_cursor%NOTFOUND;
/* context switch for implicit cursor */
SELECT c
INTO l_fetched
FROM mytable2
WHERE a = curserx.a;
END LOOP;
/* context switch to close */
CLOSE l_cursor;
END;
But that's not all! Remember that the context switch works both ways: SQL -> PL/SQL and PL/SQL -> SQL. You can reduce the overhead of going from SQL to PL/SQL by declaring your function with the UDF pragma (12c+) or defining it with the WITH FUNCTION clause (also 12c+). There is still a context switch but some of the work is done at compile time instead of run time.
So in the code below, for each invocation of the function from within the SELECT, there is a switch.
CREATE OR REPLACE FUNCTION full_name (first_in IN VARCHAR2,
last_in IN VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
RETURN first_in || ' ' || last_in;
END;
/
DECLARE
l_name VARCHAR2 (32767);
BEGIN
SELECT full_name (first_name, last_name) INTO l_name
FROM employees
WHERE employee_id = 100;
DBMS_OUTPUT.PUT_LINE (l_name);
END;
/
Finally a cautionary note: you should do everything you can to avoid executing SQL inside a function that is then called from SQL. The standard read consistency model that works for your SQL statement will not be "carried in" to the function's SQL. In other words, if you "outer" SELECT starts running at 10:00 and runs for an hour, and at 10:05, someone deletes rows from a table that is used in both the outer query and the query in the function (and commits), those two queries will be working with different states of those tables.
| {
"pile_set_name": "StackExchange"
} |
Q:
MATLAB: adding a plot to an axis
I am using plotyy to plot two vectors on different y-axes. I wish to add a third vector to one of the two axes. Can someone please tell me why the following code is not working?
[ax h1 h2] = plotyy(1:10,10*rand(1,10),1:10,rand(1,10));
hold on; plot(ax(2),1:10,rand(1,10));
??? Error using ==> plot
Parent destroyed during line creation
I simply wish to add an additional vector to one of the axes (ax(1),ax(2)) created by plotyy.
A:
Apply hold to the axis of interest.
[ax h1 h2] = plotyy(1:10,10*rand(1,10),1:10,rand(1,10));
hold(ax(2), 'on');
plot(ax(2),1:10,rand(1,10));
plotyy works by creating two axes, one on top of the other. You are carefully adding the new vector to the second axis. The hold property is also a per-axis property, so you just need to make sure that the hold is set on the same axis.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the main genre of "hacking" films?
What is the main genre of "hacking" films which have hackers as characters in the film, e.g., "Die Hard 4" or "Nikita"?
I tried to look up the genre of them but they are just Action | Crime | Thriller. Isn't there a main genre for the movies like them?
A:
It's a bit more of a buzzword rather than a formal genre, but I think what you are looking for is techno-thriller:
Techno-thrillers (or technothrillers) are a hybrid genre, drawing subject matter generally from science fiction, thrillers, spy, action and war. They include a disproportionate amount (relative to other genres) of technical details on its subject matter (typically military technology); only science fiction tends towards a comparable level of supporting detail on the technical side. The inner workings of technology and the mechanics of various disciplines (espionage, martial arts, politics) are thoroughly explored, and the plot often turns on the particulars of that exploration.
| {
"pile_set_name": "StackExchange"
} |
Q:
somatoChart in r (plot or ggplot)
I'm trying to make a replica of the somatoChart to characterize the somatotype of some athletes, I need some adjustments to get the result I expect, figure left my code, figure right what I hope.
x <- c(0,-6,6,0,-4.5,4.5,0)
y <- c(12,-6,-6,0,4.5,4.5,-7.5)
par(mar = c(2,0,0,2), mgp = c(2,1,0))
plot(x,y,pch = 20,xlab = " ",ylab = " ",xlim = c(-8,8), ylim = c(-10,16),las = 1, col = "white",axes = F)
axis(4, las = 1, yaxp = c(-10,16,13),cex.axis=0.8)
axis(1, xaxp = c(-8, 8, 16),cex.axis=0.8)
# Segmentes
segments(x0 = 0, y0=-7.5, x1 = 0, y1 = 12, lty = 2)
segments(x0 = -6, y0=-6, x1 = 4.5, y1 = 4.5, lty = 2)
segments(x0 = 6, y0=-6, x1 = -4.5, y1 = 4.5, lty = 2)
# text
windowsFonts(B=windowsFont("Bookman Old Style"))
text(0,13,"MESOMORPH", cex = 0.6,family="B", font = 2)
text(-6,-8,"ENDOMORPH",cex = 0.6,family="B", font = 2)
text(6,-8,"ECTOMORPH", cex = 0.6,family="B", font = 2)
# curves
segments(x0 = -4.5, y0=4.5, x1 = 0, y1 = 12)
segments(x0 = -4.5, y0=4.5, x1 = -6, y1 = -6)
segments(x0 = 0, y0=-7.5, x1 = -6, y1 = -6)
segments(x0 = 0, y0=-7.5, x1 = 6, y1 = -6)
segments(x0 = 4.5, y0=4.5, x1 = 6, y1 = -6)
segments(x0 = 4.5, y0=4.5, x1 = 0, y1 = 12)
Would readers make suggestions please?
A:
Perhaps using xspline can solve your problem:
x <- c(0,-6,6,0,-4.5,4.5,0)
y <- c(12,-6,-6,0,4.5,4.5,-7.5)
par(mar = c(2,0,0,2), mgp = c(2,1,0))
plot(x,y,pch = 20,xlab = " ",ylab = " ",xlim = c(-8,8), ylim = c(-10,16),las = 1, col = "white",axes = F)
axis(4, las = 1, yaxp = c(-10,16,13),cex.axis=0.8)
axis(1, xaxp = c(-8, 8, 16),cex.axis=0.8)
# Segmentes
segments(x0 = 0, y0=-7.5, x1 = 0, y1 = 12, lty = 2)
segments(x0 = -6, y0=-6, x1 = 4.5, y1 = 4.5, lty = 2)
segments(x0 = 6, y0=-6, x1 = -4.5, y1 = 4.5, lty = 2)
# text
windowsFonts(B=windowsFont("Bookman Old Style"))
text(0,13,"MESOMORPH", cex = 0.6,family="B", font = 2)
text(-6,-8,"ENDOMORPH",cex = 0.6,family="B", font = 2)
text(6,-8,"ECTOMORPH", cex = 0.6,family="B", font = 2)
xspline(y = c(-6, 4.5, 12), x = c(-6, -4.5, 0), shape = -1, lty = 2)
xspline(y = c(-6, -7.5,-6), x = c(-6, 0, 6), shape = -1, lty = 2)
xspline(y = c(-6, 4.5, 12), x = c(6, 4.5, 0), shape = -1, lty = 2)
| {
"pile_set_name": "StackExchange"
} |
Q:
Pokemon Mystery Dungeon: Gates to Infinity - How much content does the DLC give you?
The DLC's you can buy for 1.50/2.50/3.00 euro. Do they supply any rare items, a huge amount of money (from the gold dungeon), do they have any content that the game doesn't?
A:
According to this post:
Each DLC gives 3 things.
A] 1 dungeon. Usually with a special gimmick to make the game a little easier by providing easier access to something that you can already get playing without the DLC (recruitable starters, buyable TMs, etc). There is also a 99 floor DLC dungeon if a bigger challenge after clearing the postgame dungeons is more your thing.
B] 1 Music Track used for the new dungeon and also doubles as a track that gets rotated into the main/title menu screen music.
C] 1 Music track that gets rotated into the main menu music.
| {
"pile_set_name": "StackExchange"
} |
Q:
Protected HTML / CSS for js?. I can not change some attributes on running time
For business reasons (endless discussion about blog colours), we want to give "some tool" to the user (sort of techie) to play with the colour themselves.
The blog is a simple Wordpress and has some plugins (i.e. Google Calendar embedded with an iframe).
We ask the user to play in the address bar with sentences like:
javascript:document.getElementById("reply-title").style.cssText='color:#f0555f'; void 0
While this works and modifies the text colour of the selected element (the "leave a comment" text), it doesn't work for other elements, specifically one of the elements belonging to the Google Calendar iframe (the following is the date that appears on top of the calendar):
javascript:document.getElementById("currentDate1").style.cssText='color:#f0555f'; void 0
Is it possible that the items inside the iframe are in some way protected of being changed by JavaScript?
A:
Well actually... you are doing it very inefficiently.
If you have Chrome, Firefox, Internet Explorer, Opera or... Safari:
you can "Right Click" on an element of the page an inspect the DOM.
And the styling (CSS). It will be more user-friendly even for Devz.
The items in an iFrame aren't protected from this.
For chrome, check chrome devtools.
EDIT: Also try pressing CTRL+ALT+RightClick if people are blocking it ;)
| {
"pile_set_name": "StackExchange"
} |
Q:
Softkeyboard blocking EditText
I'm having the following problem:
I have an activity which enables a user to post comments on some article. When the user taps the EditText field where the comment can be posted, the softkeyboard ends up blocking the text field such that the user can't see what is being typed. How can I make sure that the EditText field is always, at least partly, visible?
A:
Add the contents of your activity to a scrollable layout and when the EditText view gets focus manually scroll the ScrollView.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't figure out how to make toggleClass work properly with window resize
When I load my page when it is over 860px wide the script works the way I want it to. It does not have the .open class on the child ul tag of li.parent class. It also adds that class when I make the page smaller.
However, I noticed when I go from the page being smaller to larger, the .open class still hangs around. And if I click on the li.parent, it throws off the script and it no longer works when the page is smaller.
Here is my script.
$(window).resize(function (){
if ( $(window).width() < 860 ) {
$(document).ready(function(){
$('li.parent').click(function(){
$(this).find('ul').toggleClass('open');
});
});
}
else {
$('ul#primary-nav').removeAttr('style');
$('li.parent').find('ul').removeClass('open');
}
});
Other scripts in the same document. Maybe they are causing a conflict?
// Mobile Menu Slide Toggle
jQuery(document).ready(function() {
jQuery('.show_nav').click(function(e) {
e.preventDefault();
jQuery('#primary-nav').slideToggle();
});
});
// For Menu Caret
jQuery(document).ready(function() {
jQuery('ul#primary-nav li').has('ul').addClass('parent');
});
Some of the CSS
ul#primary-nav li.parent ul {display: none;}
ul#primary-nav li.parent ul.open {display: block;}
Some of the HTML
<a href="#primary-nav" class="show_nav"><img src="images/hamburger-lines-white.svg" alt="Menu" width="25" height="25"></a>
<ul id="primary-nav">
<li><a href="#">About</a>
<ul>
<li><a href="#">History</a></li>
<li><a href="#">Facilities</a></li>
</ul>
</li>
<li><a href="#">Tennis</a></li>
<li><a href="#">Classes</a></li>
<li><a href="#">Calendar</a></li>
<li><a href="#">Newsletter</a></li>
<li><a href="#">Home Owners</a>
<ul>
<li><a href="#">Board of Directors</a></li>
<li><a href="#">Architectural Committee</a></li>
<li><a href="#">Documents and Forms</a></li>
</ul>
</li>
<li><a href="#">Contact</a></li>
</ul>
Been trying to figure this out for a while and looked all over this site. Could really use some help.
A:
Forget the jQuery and use a media query.
ul#primary-nav li.parent ul {display: none;}
@media only screen and (min-width: 860px) {
ul#primary-nav li.parent ul {display: block;}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Use PowerShell's type -wait with select-string to Real-Time Monitor an Application Log for a Condition and Execute an Action (like tail -f or watch)
I am trying to use PowerShell's type -wait command to monitor a log file in real time on Windows in the same way that I would use tail -f on Linux, and I want to pipe the file to another command - select-string, like grep - that will trigger an action based on a condition. On Linux, I would use watch to accomplish what I'm trying to do.
In the following example, I am trying to print the phrase "You caught a critter!" whenever a new line, which contains the string "status=Caught", is written to the log file.
while (1) {if (type -wait "$env:USERPROFILE\AppData\Roaming\CritterCatcherApp\Logs\CritterBag-170118.log" | select-string -quiet "state=Caught") {write-host "You caught a critter!"} else {continue}}
Please note that the -quiet argument for the select-string command returns True. Actually, in this example, it only returns True one time, when I first run the command, as the log file has existing lines that contain the string "status=Caught".
I do need to somehow overlook the existing strings (or, e.g., rotate the log files), but right now, the issue is that I need the PowerShell script to not only continue to tail the file, but I also need it to continue to evaluate whether each new line that is written to the file contains the given string. Then, if the string is present, I need to execute an arbitrary action, like print a line; else, continue listening for the string.
The following post indicates that the -wait argument is an option for the Get-Content cmdlet: How to monitor a windows log file in real time? . I am not sure if I should expect -wait to work with a foreach loop, as described in this post: In Powershell can i use the select-string -quiet switch within a foreach statement .
How can I modify the above PowerShell script to tail a log file and execute an action for each new line with a given string, and continue to tail the file and evaluate new lines as they are written?
A:
You can do it on the pipeline with Where-Object (?) and ForEach-Object (%):
Get-Content file -wait | ? { $_ -match "status=Caught" } | % { Write-Host "You caught a critter!" }
Each time status=Caught is detected in the file, the Write-Host in the ForEach-Object will execute
| {
"pile_set_name": "StackExchange"
} |
Q:
How to format a message in jQuery custom validator method
I am trying to write a custom method as below to validate a credit card number using jQuery validate.
jQuery.validator.addMethod("ValidateCreditCard", function(value, element, params) {
var selectedElement = $('input[name="CardType"]');
var cardType = selectedElement.filter(':checked').val();
var cardNumber = $("#CardNumber").val();
if (cardType == "MasterCard" && !value.startsWith(5)) {
return false;
}
if (cardType == "Visa" && !value.startsWith(4)) {
return false;
}
return true;
}, jQuery.validator.format("Please enter a {0} card number"));
Based on to card type radio button selection, I would like display the appropriate message.
For example, if user selects Visa credit card, then error message should be please enter a visa card number likewise for Master credit card
Any thoughts on how to pass a card type value to format the message?
A:
You can do it like below:
HTML
<form id="CHECKFORM" name="CHECKFORM">
<div>
<input type="radio" name="CardType" id="radioVisaCard" value="Visa" />
<label for="MOBILE">Visa</label>
<input type="radio" name="CardType" id="radioMasterCard" value="MasterCard" />
<label for="MOBILE">Master</label>
<input type="text" class="cardNumber" data-rule-validatecreditcard="true" />
</div>
<input type="submit" value="submit" />
</form>
JS
<script>
jQuery.validator.addMethod("ValidateCreditCard", function (value, element) {
var selectedElement = $('input[name="CardType"]');
var cardType = selectedElement.filter(':checked').val();
if (cardType == "MasterCard" && !value.startsWith(5)) {
return false;
}
if (cardType == "Visa" && !value.startsWith(4)) {
return false;
}
return true;
}, function (element) {
var selectedElement = $('input[name="CardType"]');
var cardType = selectedElement.filter(':checked').val();
var startDigit;
if (cardType == "MasterCard")
startDigit = 5;
else if (cardType == "Visa")
startDigit = 4;
return 'The field should be start with ' + startDigit + ' digit.'
});
$("#CHECKFORM").validate({
rules: {
url: "ValidateCreditCard",
}
});
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Util. to tell me how many cores are being used under Win 2003 Standard
Confusion reigns about licensing, with the No. of processors that can be engaged by various versions of 2003/ 2008 server. Now that we have 6 core AMDs and future 8 core Intels, I wonder if hardware is going to waste all over the world. I have a client that runs three Dl580 G5s (Win 2003 Server Standard), with two quad cores each. If the doc is to be believed their OS can only utilize 4 processors/cores, not the 8 that they possess.
I am looking for some type of utility that will tell me how many cores can be brought into play with a mix of Windows programs. I am not sure if benchmark programs somehow use extra cores behind Windows back which would give me a false reading on how many cores can be used.
A:
Not sure why you are confused. Microsoft has clearly stated since the release of multicore processors that they were licensing PER SOCKET, not per core (Oracle, is (was?) licensing per core, for example).
Server 2003 and 2008 are BOTH multicore aware. And 2008 R2 will increase the maximum supported cores to 256.
Being Multicore aware means that the DL580s DO see all the appropriate cores. Further, if you add in hyperthreading for some newer CPUs, you will see, for example, a single 4 core hyperthreaded cpu will appear to the OS as EIGHT processors. Task manager correctly displays these.
Keep in mind the access to the CPU is through the kernel - you CANNOT "use cores behind the back" of Windows.
As for a specific third party utility... I know of no such utility and would see no point to one so I have strong doubts one would exist or be created. In any case, such a utility would have to rely on the OS, in which case Task Manager does the trick.
A:
If you need a programmatic way, there is the environment variable NUMBER_OF_PROCESSORS or there are the WMI interfaces. But as Multiverse said, you can't use the processor without going through the OS, and Task Manager will tell you the truth.
| {
"pile_set_name": "StackExchange"
} |
Q:
Opengl texture flickering when used with mix()
I'm rendering a terrain with multiple textures that includes smooth transitions between the textures, based on the height of each fragment.
Here's my fragment shader:
#version 430
uniform sampler2D tex[3];
uniform float renderHeight;
in vec3 fsVertex;
in vec2 fsTexCoords;
out vec4 color;
void main()
{
float height = fsVertex.y / renderHeight;
const float range1 = 0.2;
const float range2 = 0.35;
const float range3 = 0.7;
const float range4 = 0.85;
if(height < range1)
color = texture(tex[0], fsTexCoords);
else if(height < range2) //smooth transition
color = mix( texture(tex[0], fsTexCoords), texture(tex[1], fsTexCoords), (height - range1) / (range2 - range1) );
else if(height < range3)
color = texture(tex[1], fsTexCoords);
else if(height < range4) //smooth transition
color = mix( texture(tex[1], fsTexCoords), texture(tex[2], fsTexCoords), (height - range3) / (range4 - range3) );
else
color = texture(tex[2], fsTexCoords);
}
'height' will always be in the range [0,1].
Here's the weird flickering I get. From what I can see they happen when 'height' equals one of the rangeN variables when using mix().
What may be the cause of this? I also tried playing around with adding and subtracting a 'bias' variable in some computations but had no luck.
A:
Your problem is non-uniform flow control.
Basically, you can't call texture() inside an if.
Two solutions:
make all the calls to texture() first then blend the results with mix()
calculate the partial derivatives of the texture coordinates (with dFdx & co., there is an example in the link above) and use textureGrad() instead of texture()
In very simple cases, the first solution may be slightly faster. The second one is the way to go if you want to have many textures (normal maps etc.) But don't take my word for it, measure.
| {
"pile_set_name": "StackExchange"
} |
Q:
Handle oauth errors with Google Ruby Client?
I'm using Google API Ruby Client (gem 'google-api-client') in a Rails Web app, and I'd like to know how to catch specific errors in the oauth flow. In particular, what should I look for in the rescue statement? Here's the function called by the redirect after the user authorizes:
require 'google/api_client'
def google_auth_finish
begin
client = Google::APIClient.new
client.authorization.client_id = GOOGLE_CLIENT_ID
client.authorization.client_secret = GOOGLE_CLIENT_SECRET
...
rescue ## WHAT GOES HERE TO IDENTIFY THE ERROR?
# Handle the error
logger.info "There was an error."
end
end
Is there a reference somewhere with defined errors? I've searched and can't find it.
A:
I know this was asked years ago, but I literally just encountered this problem and happened upon this question. You were just missing a small part. This worked for me. I am still relatively new, but in my case it prevented the program from breaking and printed out the error message, then the program continued on.
rescue Exception => error
puts "Error #{error}"
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Promise.then not executing
In the following code block only 'first promise' is logged to console. Why is that? I was trying to write a test to figure out how .then()'s execute after .catch() but was surprised when nothing besides the first promise ran. Whats going on here?
function foo() {
return new Promise((resolve, reject) => {
return console.log('first promise')
})
.then(() => console.log('first then'))
.catch(() => console.log('catch block'))
.then(() => console.log('last block'))
.then(() => resolve)
}
foo();
A:
As Yury said, you're not resolving the promise, simply returning a log.
https://jsfiddle.net/k7gL57t3/
function foo() {
var p1 = new Promise((resolve, reject) => {
resolve("Test");
})
p1.then(() => console.log('first then'))
.then(() => console.log('last block'))
.then(() => resolve)
.catch(() => console.log('catch block'));
}
foo();
| {
"pile_set_name": "StackExchange"
} |
Q:
Primefaces Warning
I am using Primefaces. I am trying to add a value from xhtml to back end. The moment I start the server it gives me the warning
May 31, 2013 8:56:38 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2341 ms
May 31, 2013 8:56:39 PM org.apache.catalina.core.ApplicationContext log
INFO: No state saving method defined, assuming default server state saving
as a result, none of the functions getting executed. After searching in the forum for a long time, i found something and inserted
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
in my web.xml. Still same problem.
Any help appreciated...
A:
I found the answer myself. I am having a page which is the index page which just includes other pages.
<h:form> <ui:include src="aaa/ddd/fff.xhtml" /></h:form>
like this. SO thats why this warning was coming. Then when I went to the actual page it did not show the warning and everything working perfectly.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the demonym for those who are born and bred in the district of Bragança, in the extreme Portuguese northeast?
There is a city in São Paulo, Brazil, called "Bragança Paulista". Those who are born there are called "bragantinos". What is the demonym for the Portuguese district of Bragança? I've heard "brigantino", "bragançano", and "braganção". Perhaps those from southern Portugal use one form and those from the north use another. I'm interested in learning which one a native from Bragança would choose to refer to himself.
A:
My source, a friend born and bred in the town of Bragança, tells me people from her home town are brigantinos or bragançanos. Brigantino is the more common demonym, and derives from the town's ancient name Brigantia. I am not aware of a name for people from the distrit of Bragança as such, or for people from any other Portuguese district for that matter.
People in Portugal identify themselves with their municipality, which, unlike districts, are very old entities with directly elected officials. The distric of Bragança comprises twelve municipalities. There are names for people from each of these: mirandês or mirandense for someone from Miranda do Douro, vila-florense for someone from Vila Flor, and so on.
A:
In Portugal, those from Bragança are brigantinos or bragantinos.
Wikipedia also registers bragançano, braganção, and bragancês, but as a portuense I'm not familiar with these.
It's difficult to be sure; because of the complexity of the demonyms (albicastrense, escalabitano, oliventino, etc), they are often not very well-known. This could easily explain the origin of the different registers.
Further reading: WP>lista de gentílicos de Portugal
| {
"pile_set_name": "StackExchange"
} |
Q:
Как правильно сказать: "на клею" либо "на клее"?
Контекст такой: "Это изделие выполнено только на клею(е?) и шкантах, без каких-либо крепежей из металла".
A:
В орфографическом словаре:
клей, кле́я и кле́ю, предл. в кле́е и в (на) клею́, мн. клеи́, -ёв.
В словаре русского словесного ударения:
клей, -я, о кле́е, в кле́е и в клею́, на клею́; мн. (в знач. сортов) клеи́, -ёв.
В толковом словаре Ожегова:
КЛЕЙ, -я (-ю), о клее, на клее и на клею, в клее и в клею, м. Липкий затвердевающий состав для плотного соединения, скрепления частей чего-н. Канцелярский к. Столярный к. Весь в клею (испачкан клеем). Обувь на клею. || прил. клеевой, -ая, -ое. Клеевая краска (приготовленная на клею).
Особая форма предложного падежа — это так называемый местный падеж, используемый только с предлогами в и на. Подробные разъяснения есть на нашем сайте.
Ваше предложение я бы написала так:
Это изделие выполнено только (на чём?) на клею и шкантах, без каких-либо крепежей из металла.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python2.7 socket error 37 "Operation already in progress"
I'm making a script that reads a file full of proxy servers and checks if they are up or down.
import socket
proxyFile = open("proxies.txt","r");
lines = proxyFile.readlines();
class Colors:
none = "\033[0m";
red = "\033[31m";
green = "\033[32m";
yellow = "\033[33m";
blue = "\033[34m";
purple = "\033[35m";
cyan = "\033[36m";
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
sock.settimeout(3);
for line in lines:
line = line.replace(":"," : ");
reader = line.split();
ip = reader[reader.index(":") - 1];
port = int(reader[reader.index(":") + 1]);
try:
sock.connect((ip,port));
print Colors.cyan + ip + ":" + str(port) + Colors.none + " is " + Colors.green + "UP";
sock.close();
except socket.timeout:
print Colors.cyan + ip + Colors.yellow + ":" + Colors.cyan + str(port) + Colors.none + " is " + Colors.red + "DOWN";
It seems that the file reads fine and the socket creates, but it only connects to one server then it gives the error.
Proxy File:
1.0.134.56:8080
1.165.192.248:3128
1.172.185.143:53281
1.179.156.233:8080
1.179.164.213:8080
1.179.185.253:8080
1.192.242.191:3128
1.20.169.166:8080
1.20.179.68:8080
1.20.99.163:8080
A:
You can't re-connect a socket. Once it's connected, it's connected. Even if you call close:
all future operations on the socket object will fail.
The right answer is to create a new socket each time through the loop, whether with create_connection or with socket and connect. For example, change your try block to this:
try:
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
sock.settimeout(3);
sock.connect((ip,port));
print Colors.cyan + ip + ":" + str(port) + Colors.none + " is " + Colors.green + "UP";
sock.close();
except socket.timeout:
print Colors.cyan + ip + Colors.yellow + ":" + Colors.cyan + str(port) + Colors.none + " is " + Colors.red + "DOWN";
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Ionic application as web app
Can I build an ionic application and use it as web application with full capabilities as the mobile part ? Or ionic have 100% efficiency on phones ?
A:
As for running ionic on as a web application. yes you can do that. but one thing you'll need to consider when developing your application. check your dependencies and libraries, and be sure that they support web application. else you should be fine.
As for the efficiency part, it is not optimal, but you can enhance the performance. something that ionic does that will slow your app is loading all your application in one JS file, that delays the lunch, to avoid that use lazy loading to load your app's components.
Let me know if you have any further questions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Styling input placeholder when input is read-only
I'm trying to style my input placeholder property only when the input is read-only but I can't seem to get the two selectors to work together, is this possible? I've tried a few variations but thought the below should work;
input:read-only + ::placeholder { color: black !important; }
...and to ensure max browser comptibility
input:read-only + ::-webkit-input-placeholder, input:read-only + ::placeholder, input:-moz-read-only + ::placeholder, input:read-only + ::-ms-input-placeholder { color: black !important; }
None of these work, is this possible? Where am I going wrong?
A:
The Placeholder is not a child of the input so no space is needed in the selector.
input:read-only::placeholder {
color: red
}
<input type="text" placeholder="You can't type here!" readonly>
A:
You can use the following solution:
input[readonly]::placeholder {
color: blue !important;
}
<input type="text" placeholder="Hey StackOverflow" readonly/>
<input type="text" placeholder="Hey StackOverflow"/>
Browser Compatibility / Can I use?
https://caniuse.com/#feat=css-placeholder
https://caniuse.com/#feat=css-read-only-write
Why your CSS rules doesn't work?
Your CSS rules to format the placeholder tries to access a following placeholder (placeholder after <input> element). The placeholder is on the <input> element itself, so your rules doesn't match.
p + p {
color:blue;
}
<p>Hello</p>
<p>StackOverflow</p>
more: Explanation of the + sign in CSS rules
| {
"pile_set_name": "StackExchange"
} |
Q:
Could not load type 'System.Net.Security.SslStream'
I've this simple C# program:
using Npgsql;
public class App {
public static void Main(string[] args) {
const string CONNECTION_STRING = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase";
using (var conn = new NpgsqlConnection(CONNECTION_STRING)) {
conn.Open();
}
}
}
and I compile it with mono (mcs):
mcs -target:exe -lib:bin -r:System.Data.dll -r:Npgsql.dll -r:System.dll -r:Mono.Security.dll -out:bin/ssl.exe src/App.cs
when I execute, an error thrown:
Unhandled Exception:
System.TypeLoadException: Could not load type 'System.Net.Security.SslStream' from assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
at Npgsql.NpgsqlConnector.Open () <0x4155f7f0 + 0x00115> in <filename unknown>:0
at Npgsql.NpgsqlConnectorPool.GetPooledConnector (Npgsql.NpgsqlConnection Connection) <0x4155c8d0 + 0x00a4f> in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException: Could not load type 'System.Net.Security.SslStream' from assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
at Npgsql.NpgsqlConnector.Open () <0x4155f7f0 + 0x00115> in <filename unknown>:0
at Npgsql.NpgsqlConnectorPool.GetPooledConnector (Npgsql.NpgsqlConnection Connection) <0x4155c8d0 + 0x00a4f> in <filename unknown>:0
My Npgsql.dll version
$ monop2 -r Npgsql.dll
Assembly Information:
Npgsql
Version=2.2.0.0
Culture=neutral
PublicKeyToken=5d8b90d52f46fda7
My compiler:
$ mcs --version
Mono C# compiler version 4.4.0.0
$ mono --version
Mono JIT compiler version 4.4.0 (Stable 4.4.0.40/f8474c4 Mon Mar 28 12:22:29 UTC 2016)
Copyright (`u`C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
TLS: __thread
SIGSEGV: altstack
Notifications: epoll
Architecture: amd64
Disabled: none
Misc: softdebug
LLVM: supported, not enabled.
GC: sgen
Finally, my environment:
$ uname --all
Linux abe 4.5.0-1-ARCH #1 SMP PREEMPT Tue Mar 15 09:41:03 CET 2016 x86_64 GNU/Linux
Thank you
A:
I have one question - do you have library Mono.Security.dll inside bin folder? If so, please delete it and try again.
| {
"pile_set_name": "StackExchange"
} |
Q:
MVC 4 prevent script bundle from rendering on specific view
Is there a way to prevent the script bundle from rendering on a specific view? I would like to use the _layout page and its script bundle by default on most of the views. I am having an issue with a specific view where I am using a jQuery grid and have included the scripts I need in that view. The bundle addition from the layout page is breaking my view with the grid.
A:
Thanks kehrk. What I did was create another layout page without the Scripts.Render section, _LayoutPCA and modified the _ViewStart page similar to your code like this:
string currentController = ViewContext.RouteData.Values["controller"].ToString();
if(currentController == "PCA")
{
Layout = "~/Views/Shared/_LayoutPCA.cshtml";
}
else
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
This way I can load the _LayoutPCA for this controller only and load the default layout page for the rest of the views. This will of course affect all the view for the PCAController but is ok for now.
| {
"pile_set_name": "StackExchange"
} |
Q:
opencv- Getting std::length_error' what(): vector::_M_fill_insert when computing HOG features from 25*125 eye image
When I am calculating the HOG features of eye image of size 25*125. then getting the error message terminate called after throwing an instance of 'std::length_error'
what(): vector::_M_fill_insert
HOGDescriptor hog;
vector<float> ders;
vector<Point>locs;
hog.compute(img,ders,Size(4,4),Size(0,0),locs);
Mat Hogfeat;
Hogfeat.create(ders.size(),1,CV_32FC1);
for(int i=0;i<ders.size();i++)
{
Hogfeat.at<float>(i,0)=ders.at(i);
}
Can any one tell me the solution?
A:
One side of the image is smaller than the descriptor and therefore the computation fails.
If I use the following line, the computation works for me:
hog.compute(img,ders,Size(3,3),Size(0,0),locs);
The size of blocks is 8. So 3 * 8 = 24 <= 25 but 4 * 8 = 32 > 25.
The solution depends on what exactly you want to achieve and which compromise you are willing to make.
You could just use the smaller descriptor which might lead to some loss in descriptiveness for other images. Or you could scale or pad the images that are too small which will probably make their descriptors less useful but won't affect the others.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to select/init first value in html select option after data loads thru Angular 2 observable?
I have an html select with options that looks like this:
<select [(ngModel)]="role" (ngModelChange)="roleChanged($event)">
<option *ngFor="#role of roles" [ngValue]="role">{{role.Name}}</option>
</select>
roles[] gets assigned in a subscribe of an observable from my service. Everything is working fine except the select is empty initially even after roles[] is loaded. I would like the select drop down to display the first option immediately when roles[] is loaded from the service. And then have that change "role" too.
I'm thinking either using ngInit on the select, or the option, but can't seem to get it to work. Also I thought about assigning role in the component after the observable is returned but I can't figure that out / know if that's possible because roles[0] is always null before roles[] is loaded.
Here's the subscribe code if that is important:
getDivisonTeamRoles() {
this._divisonProposalService.getDivisionTeamRoles()
.subscribe(
roles => this.roles = roles,
error => this.errorMessage = <any>error);
}
A:
I figured it out. In the subscribe () function you can add multiple lines of code there and call functions, assign other variables, etc. Like so..
.subscribe(
roles => {
this.roles = roles;
this.role = this.roles[0];
this.getEmployeesByRole();
},
error => this.errorMessage = <any>error);
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery slideDown in IE9 - content disappears after animation finishes
I've had this problem twice on two different sites. It works in all browsers other than IE9.
I have a div being opened and closed using jquery slideup and slideDown (the same problem happens with slideToggle). I'm able to see the content of the div as it slides down, but as soon as the animation stops, the content disappears.
Heres an example of this problem http://www.ohnuts.com/searchResults.cfm?criteria=cashews&search=all click on the "more categories" link.
Has anyone else experienced this problem, and are there any workarounds? I can change it to just do a simple show/hide, that works fine, but i'd like to keep the effect of it opening.
A:
2 thumbs up with Nick's answer.
But by the time IE team will solve the problem, you will probably be on another project.
Here is what worked for me with IE7 that will certainly works on IE9.
On the DIV you set a slideDown effect, add this to your CSS:
overflow: hidden;
Good day!
A:
Honest suggestion here, don't fix it, report it as a bug to the IE9 team but don't spend any time fixing their bug.
This should be fixed in IE9 final, and the end result will just be wasted development time on your end...betas are buggy, they've always been buggy and will always be buggy...they wouldn't be called betas otherwise.
| {
"pile_set_name": "StackExchange"
} |
Q:
Switching from "if" to "elseif" breaks code
I'm using multiple if statements to check a containing div, and output an image based on the container name. The code was working fine until I add a final "else" or change the if's out to elseif and I can't figure out why that's happening. When I try to add the else or elseif, the entire page fails to load. Any idea why this is happening?
<?php
if($viewMore['container_type'] == 'Large IMG' || $viewMore['container_type'] == 'Gallery') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'large_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$large = 0; foreach ($photoArray as $photo => $upload): if (++$large == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach ?>
<?php } ?>
<?php
elseif($viewMore['container_type'] == 'Medium IMG') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'small_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$medium = 0; foreach ($photoArray as $photo => $upload): if (++$medium == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach; ?>
<?php } ?>
<?php else { ?> SOMETHING HERE <?php } ?>
EDIT:
Other notes
I've tried wrapping the break; in brackets because I thought that piece following the count might be messing with something. Also removing the counter altogether or adding a semi colon after the endforeach didn't help.
A:
Whenever you close your PHP block, think about all the text/HTML outside it being put into PHP's echo function.
What gave me alarm bells was this part:
<?php } ?>
<?php else { ?> ...
What that translates into is:
if (...) {
} echo "[whitespace]"; else {
}
which clearly makes your else block unexpected.
You should not close the PHP block between your closing if and opening else, i.e. do this instead:
...
} else {
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Joining Tables and Displaying Result as Text, in one column
I need to join two columns from two tables and display them in a specific order
Table1 and ColumnNM
Table2 and ColumnDESC
The Primary Key is ColumnID
I have multiple rows of ColumnDESC for each ColumnNM. So i have to display in the following format:
ColumnID ColumnNM
-------------------
ColumnDESC
ColumnDESC
ColumnDESC
ColumnDESC
ColumnID ColumnNM
-------------------
ColumnDESC
ColumnDESC
ColumnID ColumnNM
-------------------
ColumnDESC
ColumnDESC
ColumnDESC
I have to display results to text, instead of grid. Any suggestions on how to do this?
I have to create it as a stored procedure. Any help is appreciated. Below is as far as i got:
DECLARE @Name nvarchar(max),
@Lesson nvarchar(max),
@lb nvarchar(max)
SET @lb = '----------------------------------------------------'
SELECT @Name = Module.Name
FROM Module
JOIN Lesson ON Module.ModuleSequence = Lesson.ModuleSequence
WHERE Module.ModuleSequence = 1
PRINT '1 ' + @Name
PRINT @lb
SELECT Lesson.Description
FROM Module
JOIN Lesson ON Module.ModuleSequence = Lesson.ModuleSequence
WHERE Module.ModuleSequence = 1
But I think I'm way off.
..........................................OKAY, EDIT, after John Tabernik suggestion i got this......................................
(P.S. sorry about adding a comment to your answer, just learning how to use stackoverflow)
SELECT M.Name, L.Description
FROM Module M
JOIN Lesson L
ON M.ModuleSequence = L.ModuleSequence
ORDER BY M.Name, L.Description
I end up getting the M.Name repeated four times as there are four different L.Description for the first M.Name, and different amounts for all the other M.Name's.
Example:
M.Name | L.Description
-----------------------------
A | 1
A | 2
A | 3
B | 1
B | 2
C | 1
C | 2
C | 3
But i need it to output like this:
A |
-----
1 |
2 |
3 |
B |
-----
1 |
2 |
C |
-----
1 |
2 |
A:
Sorry for getting back a bit late, but I have solved what I needed. I think I worded the question a bit off. Nonetheless, below is the code i needed. Hope it inspires anyone who has similiar problem:
CREATE PROCEDURE ShowModuleWithLessons
@CourseID int = 0
AS
BEGIN
SET NOCOUNT ON
DECLARE @MS INT
DECLARE @ModuleCount INT
SET @MS = 0
SET @ModuleCount = (Select COUNT(Module.ModuleSequence) FROM Module WHERE Module.CourseID = @CourseID)
IF EXISTS (SELECT * FROM Module WHERE Module.CourseID = @CourseID)
BEGIN
WHILE @MS < @ModuleCount
BEGIN
SET @MS=@MS+1
DECLARE @Name nvarchar(max),
@Lesson nvarchar(max),
@CID INT
SELECT @Name = Module.Name,
@CID = @MS
FROM Module
JOIN Lesson ON Module.ModuleSequence = Lesson.ModuleSequence
WHERE Module.ModuleSequence = @MS
PRINT CONVERT(VARCHAR(2),@MS) + '. ' + @Name
SELECT Lesson.Description AS Lessons
FROM Module
JOIN Lesson ON Module.ModuleSequence = Lesson.ModuleSequence
WHERE Module.ModuleSequence = @MS
END
END
ELSE
BEGIN
PRINT 'Course with ID ' + CONVERT(VARCHAR(2),@CourseID) + ' does not exists'
END
| {
"pile_set_name": "StackExchange"
} |
Q:
Loop a function or use multiple?
I'm getting some data from a mysql database using ajax, data.one, data.two and data.three. Each with a different string.
I also have three divs, .one .two and .three.
How can I append data.one to the div .one and so on with all three divs and data without repeating a code like this for all three divs?
$('.one').append(data.one);
$('.two').append(data.two);
$('.three').append(data.three);
My own thought was to make a function that repeats but I don't know how to accomplish that..
I guess this is not a big deal with only three strings and divs but the site I'm building is using more of them and I want the code to look clean.
Thanks in advance!
A:
For that simple, particular example:
$.each(data, function(key, value){
$('.'+key).append(value);
});
JSFiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Show line number on Borland C++Builder 6 (2002)
I know it's a old IDE, but in my job I have to work with it.
I spend a couple of days searching where could I set the line numbers to show on the left side of the text editor, but I couldnt find.
I'm still hoping it's possible, never saw any IDE that didn't have that.
A:
You'll not find it. Only Borland c++ 2005 and higher can do this. Sorry.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to determine if search string is wrapped by anchor tag in larger string- javascript regular expressions
var content = "This is dummy <a href='#'>content</a> for my <a href='#'>Search String</a> and here is another Search String without an anchor tag",
searchString = "Search String";
Using regular expressions in javascript/jquery, how can I determine if the FIRST searchString in content string is wrapped in an anchor tag or not? I only need a boolean true/false to determine if this is directly wrapped by
A:
The most reliable way is to parse the HTML and search recursively for the first occurence of the text. Then, check whether the/a parent of that text node is an anchor.
Here is a generic function I've written:
/**
* Searches for the first occurence of str in any text node contained in the given DOM
* @param {jQuery} dom A jQuery object containing your DOM nodes
* @param {String} str The string you want to search for.
* @returns {Object} Returns either null or the text node if str was found.
*/
function searchFirstTextOccurrence(dom, str) {
var foundNode = null;
dom.contents().each(function (idx, node) {
if (node.nodeType == Node.TEXT_NODE) {
if (node.textContent.indexOf(str) !== -1) {
foundNode = node;
// break out of each()
return false;
}
} else if (node.nodeType == Node.ELEMENT_NODE) {
var foundInnerNode = searchFirstTextOccurrence($(node), str);
if (foundInnerNode) {
foundNode = foundInnerNode;
// break out of each()
return false;
}
}
});
return foundNode;
}
Your use case:
→ jsFiddle
var content = "This is<div> dummy <a href='#'>content</a> for my <a href='#'>Search String</a> and</div> here is another Searchx String without an anchor tag";
var searchString = "Search String";
var dom = $("<div>" + content + "</div>");
var firstOccurence = searchFirstTextOccurrence(dom, searchString);
if ($(firstOccurence).closest("a").length > 0) {
console.log("Yep");
} else {
console.log("No");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Exporting image styles in Drupal 7?
I know that there is a hook to programmatically define image styles in code but I can't find anyway to export ones that already exist in the database to code?
A:
The best way to do this is almost always by using the features module.
That being said if you do not want to use feature this is how you can do it.
In your module you're going to want to define a hook_image_default_styles().
If you already have a style on the database that you would like to define in this hook the best way to accomplish this is by doing something like
$style_name = "name_of_your_style";
$style = image_style_load($style_name);
//$style now has everything you need for your hook_image_default_styles definition.
It does has some extra stuff in there that can be removed such as the isid, ieid, and storage keys. You should remove those keys when using hook_image_default_styles.
If you want to find out how other items are exported out the best bet would be to look at the feature module. In there there's a directory call includes. There's going to be a file in there for everything that can be exported out in core. So you can use that for examples on how to export out styles, filters, field, etc.
Hope this answers your question.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proof for additivity of cumulants
If one does not define cumulants via the cumulant generating function (cgf), e.g. because the cgf does not exist, then an alternative way is to use the recusion
\begin{align*}
\kappa_n=\mu'_n-\sum_{m=1}^{n-1}{n-1 \choose m-1}\kappa_m \mu_{n-m}',
\end{align*}
where $\mu_i'$ denotes the $i$th uncentered moment.
For this definition, what is the best way to show that the cumulants are additive under an independence assumption? More precisely, how do we show that
\begin{align*}
\kappa_n(X+Y) = \kappa_n(X) + \kappa_n(Y),
\end{align*}
if $X$ and $Y$ are two independent random variables?
A:
I assume all your moments are finite. In that case, a simple proof is to approximate your random variable by truncation, use the additivity for the approximated cummulants, and then pass to the limit using dominated convergence.
| {
"pile_set_name": "StackExchange"
} |
Q:
Создать таблицу в html-документе через js, используя данные json?
Нужно создать таблицу в html-документе, используя данные json (создать локальную модель данных) на чистом js. Итоговый вариант должен выглядеть как на картинке. Как это сделать?
A:
Принимаешь json в переменную(для примера локальная переменная data)
let data = {
people1 : {
name : "vasja",
jan : 9,
mar: 6,
feb : 0
},
people2 : {
name : "peta",
jan : 1,
mar: 63,
feb : 10
}
}
Далее вы должны запустить цикл по объекту и вписать их значения в таблицу. В примере реализована возможноть внесения значений в tbody, разберитесь и сделайте вывод значений в thead
function createTable() {
var body = document.getElementsByTagName("body")[0];
var table = document.createElement('table');
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
for (var key in data) {
var person = data[key];
var row = document.createElement("tr");
for(var key in person) {
var td = document.createElement("td");
var cellText = document.createTextNode(person[key]);
td.appendChild(cellText);
row.appendChild(td);
}
tbody.appendChild(row);
}
body.appendChild(table);
table.appendChild(thead);
table.appendChild(tbody);
}
createTable();
| {
"pile_set_name": "StackExchange"
} |
Q:
Android : Not able to find the reason of NullPointerException
I am working on a form in android where I render values of one dropdown by selecting the value of another dropdown which is placed on top of current drop down.
So here I am selecting one University from University dropdown and on select I am rendering the values of Institutions and adding them to institution dropdown then I am selecting one Institution from Institution dropdown.
Till here everything is fine but after that if I am again changing the University then app is crashing.
Problem is, in logcat it is showing NullPointerException but it is not showing the line number where it is crashing or cause of crashing.
Logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.Spinner.makeAndAddView(Spinner.java:548)
at android.widget.Spinner.layout(Spinner.java:496)
at android.widget.Spinner.onLayout(Spinner.java:460)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1670)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1528)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1441)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.widget.ScrollView.onLayout(ScrollView.java:1470)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1670)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1528)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1441)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1670)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1528)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1441)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14243)
at android.view.ViewGroup.layout(ViewGroup.java:4490)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2230)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1994)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1181)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4942)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
at android.view.Choreographer.doCallbacks(Choreographer.java:579)
at android.view.Choreographer.doFrame(Choreographer.java:548)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
EducationalSchoolCollege.java
public class EducationalSchoolCollege extends AppCompatActivity {
private RadioGroup rg__educational_type;
private RadioButton radioeduButton;
Spinner university,instituition,degree,stream,tenureType,tenureLevel,cycleSpinner;
String student_uuid,student_name,email_id,selectedTypeIs="";
Map<String,String> educationSubmitMapData = new HashMap<>();
Map<String,String> universityListMap = new HashMap<>();
Map<String,String> instituteListMap = new HashMap<>();
List<String> universityList = new ArrayList<>();
List<String> instituteList = new ArrayList<>();
List<String> degreeList = new ArrayList<>();
List<String> streamList = new ArrayList<>();
List<String> tenureTypeList = new ArrayList<>();
List<String> tenureLevelList = new ArrayList<>();
List<String> cycleList = new ArrayList<>();
List<String> universityNameList = new ArrayList<>();
List<String> instituteNameList = new ArrayList<>();
List<String> degreeNameList = new ArrayList<>();
List<String> streamNameList = new ArrayList<>();
List<String> tenureNameList = new ArrayList<>();
List<String> tenureLevelNameList = new ArrayList<>();
List<String> cycleNameList = new ArrayList<>();
String university_uuid,institute_uuid,degree_uuid,stream_uuid,tenure_uuid,tenure_level_uuid,cycle_uuid,degree_name;
Button submitEducationalBtn;
SharedPreferences afterClassPref;
AfterClassApp controller;
public ProgressDialog progdialog;
TextView clickHereId;
String fromProfile = "",genreic_user="";
//avinash
// TextView textView4;
TextView degreeText,streamText,tenureText,cycleText;
EditText edt_instituition_other;
boolean selectedIsOther=false;
boolean isCheckedRadio = false;
//avinash
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.educational_school_college);
controller = (AfterClassApp) getApplicationContext();
afterClassPref = getApplicationContext().getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
student_uuid = afterClassPref.getString("studentUUID", null);
student_name = afterClassPref.getString("studentName", null);
email_id = afterClassPref.getString("studentEmail", null);
university = (Spinner) findViewById(R.id.university);
instituition = (Spinner) findViewById(R.id.instituition);
degree = (Spinner) findViewById(R.id.degree);
stream = (Spinner) findViewById(R.id.stream);
tenureType = (Spinner) findViewById(R.id.tenure);
tenureLevel = (Spinner) findViewById(R.id.tenureLevel);
cycleSpinner = (Spinner) findViewById(R.id.cycle);
submitEducationalBtn = (Button) findViewById(R.id.submitEducationalBtn);
clickHereId = (TextView) findViewById(R.id.clickHereId);
//avinash
edt_instituition_other = (EditText)findViewById(R.id.edt_instituition_other);
degreeText=(TextView)findViewById(R.id.degreeText);
streamText=(TextView)findViewById(R.id.streamText);
tenureText=(TextView)findViewById(R.id.tenureText);
cycleText=(TextView)findViewById(R.id.cycleText);
// textView4 = (TextView)findViewById(R.id.textView4);
rg__educational_type = (RadioGroup) findViewById(R.id.rg__educational_type);
clickHereId.setVisibility(View.GONE);
if (Build.VERSION.SDK_INT < 21) {
rg__educational_type.setPadding(3,3,3,3);
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.containsKey("from_profile")){
fromProfile = extras.getString("from_profile");
}
if (extras.containsKey("genreic_user")){
genreic_user = extras.getString("genreic_user");
}
}
//G Analytics
if (!Constants.IS_EMAIL_EXIT) {
Tracker tracker = ((AfterClassApp) getApplication()).getTracker(AfterClassApp.TrackerName.APP_TRACKER);
tracker.setScreenName("MyAfterClass EducationalSchoolCollege");
tracker.send(new HitBuilders.AppViewBuilder().build());
}
rg__educational_type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int selectedId = rg__educational_type.getCheckedRadioButtonId();
radioeduButton = (RadioButton) findViewById(selectedId);
instituition.setAdapter(null);
degree.setAdapter(null);
stream.setAdapter(null);
tenureType.setAdapter(null);
tenureLevel.setAdapter(null);
cycleSpinner.setAdapter(null);
if(radioeduButton.getText().toString().equals("School")){
edt_instituition_other.setVisibility(View.GONE);
isCheckedRadio = true;
clickHereId.setVisibility(View.GONE);
setAdapter(university,universityNameList);
universityList.clear();
instituteList.clear();
degreeList.clear();
streamList.clear();
tenureTypeList.clear();
tenureLevelList.clear();
cycleList.clear();
universityNameList.clear();
instituteNameList.clear();
degreeNameList.clear();
streamNameList.clear();
tenureNameList.clear();
tenureLevelNameList.clear();
cycleNameList.clear();
firstTimeSchoolUserData("university",null,null,null,null);
selectedTypeIs = "board";
degreeText.setVisibility(View.GONE);
degree.setVisibility(View.GONE);
stream.setVisibility(View.GONE);
tenureType.setVisibility(View.GONE);
cycleSpinner.setVisibility(View.GONE);
streamText.setVisibility(View.GONE);
tenureText.setVisibility(View.GONE);
cycleText.setVisibility(View.GONE);
}
if(radioeduButton.getText().toString().equals("College")){
edt_instituition_other.setVisibility(View.GONE);
isCheckedRadio = true;
if ("yes".equalsIgnoreCase(genreic_user)){
clickHereId.setVisibility(View.GONE);
}else{
clickHereId.setVisibility(View.VISIBLE);
}
setAdapter(university,universityNameList);
universityList.clear();
instituteList.clear();
degreeList.clear();
streamList.clear();
tenureTypeList.clear();
tenureLevelList.clear();
cycleList.clear();
universityNameList.clear();
instituteNameList.clear();
degreeNameList.clear();
streamNameList.clear();
tenureNameList.clear();
tenureLevelNameList.clear();
cycleNameList.clear();
firstTimeUserData("university", null, null,null,null,null,null,null);
selectedTypeIs = "college";
degreeText.setVisibility(View.VISIBLE);
degree.setVisibility(View.VISIBLE);
stream.setVisibility(View.VISIBLE);
tenureType.setVisibility(View.VISIBLE);
cycleSpinner.setVisibility(View.VISIBLE);
streamText.setVisibility(View.VISIBLE);
tenureText.setVisibility(View.VISIBLE);
cycleText.setVisibility(View.VISIBLE);
}
}
});
// avinash
clickHereId.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(EducationalSchoolCollege.this, OtherFirstTimeEducational.class);
startActivity(intent);
}
});
// setAdapter(university,universityList);
// firstTimeUserData("university",null,null,null,null,null,null,null);
university.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
String seluniversity = (String) university.getSelectedItem();
instituteList.clear();;
degreeList.clear();
streamList.clear();
tenureTypeList.clear();
tenureLevelList.clear();
cycleList.clear();
instituteNameList.clear();;
degreeNameList.clear();
streamNameList.clear();
tenureNameList.clear();
tenureLevelNameList.clear();
cycleNameList.clear();
Log.d("UNI ","seluniversity "+ seluniversity+ " pos:: "+position);
// clear on proper selecting
// clear on proper selecting
if ("board".equalsIgnoreCase(selectedTypeIs)){
//Todo
university_uuid = universityListMap.get(seluniversity);
firstTimeSchoolUserData("institute",university_uuid,null,null,null);
}else{
if (!"Select".equalsIgnoreCase(seluniversity)){
university_uuid = universityList.get(position-1);
educationSubmitMapData.put("university_uuid",university_uuid);
Log.d("UNI ", "university_uuid "+university_uuid);
// firstTimeUserInstitutionData("institute",university_uuid);
firstTimeUserData("institute",university_uuid,null,null,null,null,null,null);
}else{
university_uuid = null;
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
instituition.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
String selInstitute = (String) instituition.getSelectedItem();
degreeList.clear();
streamList.clear();
tenureTypeList.clear();
tenureLevelList.clear();
cycleList.clear();
degreeNameList.clear();
streamNameList.clear();
tenureNameList.clear();
tenureLevelNameList.clear();
cycleNameList.clear();
if ("board".equalsIgnoreCase(selectedTypeIs)) {
//Todo
institute_uuid = instituteListMap.get(selInstitute);
if ("other".equalsIgnoreCase(selInstitute)){
// TODO: Hide edittext box and show here
edt_instituition_other.setVisibility(View.VISIBLE);
selectedIsOther=true;
}else{
selectedIsOther=false;
edt_instituition_other.setVisibility(View.GONE);
}
tenureLevelList.clear();
firstTimeSchoolUserData("tenure_level", university_uuid, institute_uuid, null, null);
} else {
if (!"Select".equalsIgnoreCase(selInstitute)) {
// int position = university.getSelectedItemPosition();
if(instituteList.size()==0){
return;
}
edt_instituition_other.setVisibility(View.GONE);
institute_uuid = instituteList.get(position - 1);
educationSubmitMapData.put("institute_uuid", institute_uuid);
// firstTimeUserDegreeData("degree", university_uuid, institute_uuid);
firstTimeUserData("degree", university_uuid, institute_uuid, null, null, null, null, null);
} else {
institute_uuid = null;
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
degree.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
String selInstitute = (String) degree.getSelectedItem();
streamList.clear();
tenureTypeList.clear();
tenureLevelList.clear();
cycleList.clear();
streamNameList.clear();
tenureNameList.clear();
tenureLevelNameList.clear();
cycleNameList.clear();
if (!"Select".equalsIgnoreCase(selInstitute)){
// int position = university.getSelectedItemPosition();
if(degreeList.size()==0){
return;
}
degree_uuid = degreeList.get(position-1);
degree_name = degreeNameList.get(position-1);
// Log.d("degree_name",""+degree_name);
educationSubmitMapData.put("degree_uuid",degree_uuid);
// firstTimeUserDegreeData("degree", university_uuid, institute_uuid);
firstTimeUserData("stream",university_uuid,institute_uuid,degree_uuid,null,null,null,null);
}else{
degree_uuid = null;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
stream.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
String selInstitute = (String) stream.getSelectedItem();
tenureTypeList.clear();
tenureLevelList.clear();
cycleList.clear();
tenureNameList.clear();
tenureLevelNameList.clear();
cycleNameList.clear();
if (!"Select".equalsIgnoreCase(selInstitute)){
// int position = university.getSelectedItemPosition();
if(streamList.size()==0){
return;
}
stream_uuid = streamList.get(position-1);
educationSubmitMapData.put("stream_uuid",stream_uuid);
// firstTimeUserDegreeData("degree", university_uuid, institute_uuid);
firstTimeUserData("tenure_type",university_uuid,institute_uuid,degree_uuid,stream_uuid,null,null,null);
}else{
stream_uuid = null;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
tenureType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
String selInstitute = (String) tenureType.getSelectedItem();
tenureLevelList.clear();
cycleList.clear();
tenureLevelNameList.clear();
cycleNameList.clear();
if (!"Select".equalsIgnoreCase(selInstitute)){
// int position = university.getSelectedItemPosition();
if(tenureTypeList.size()==0){
return;
}
tenure_uuid = tenureTypeList.get(position-1);
educationSubmitMapData.put("tenure_type",tenure_uuid);
// firstTimeUserDegreeData("degree", university_uuid, institute_uuid);
firstTimeUserData("tenure_level",university_uuid,institute_uuid,degree_uuid,stream_uuid,tenure_uuid,null,null);
}else{
tenure_uuid = null;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
tenureLevel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
String selInstitute = (String) tenureLevel.getSelectedItem();
cycleList.clear();
cycleNameList.clear();
if (!"Select".equalsIgnoreCase(selInstitute)){
// int position = university.getSelectedItemPosition();
if(tenureLevelList.size()==0){
return;
}
tenure_level_uuid = tenureLevelList.get(position-1);
educationSubmitMapData.put("tenure_level",tenure_level_uuid);
// firstTimeUserDegreeData("degree", university_uuid, institute_uuid);
firstTimeUserData("cycle",university_uuid,institute_uuid,degree_uuid,stream_uuid,tenure_uuid,tenure_level_uuid,null);
}else{
tenure_level_uuid = null;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
cycleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
String selInstitute = (String) cycleSpinner.getSelectedItem();
if (!"Select".equalsIgnoreCase(selInstitute)){
// int position = university.getSelectedItemPosition();
if(cycleList.size()==0){
return;
}
cycle_uuid = cycleList.get(position-1);
educationSubmitMapData.put("cycle",cycle_uuid);
// firstTimeUserDegreeData("degree", university_uuid, institute_uuid);
// firstTimeUserData("cycle",university_uuid,institute_uuid,degree_uuid,stream_uuid,tenure_uuid,cycle_uuid,null);
}else{
cycle_uuid = null;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
A:
You should not do spinner.setAdapter(null); Instead of this you can use mySpinner.setEnabled(false) . Although its not same but you have to compromise
| {
"pile_set_name": "StackExchange"
} |
Q:
Avoid mobile website redirection when trying to get an XML feed on Android
I'm trying to get an xml feed from a website, nothing really special.
My problem is, when I'm trying to get my feed from my Android application, I'm automatically redirected to the mobile version of the website at the home page. This mean that the feed I get is the HTML page of the mobile website, not the xml file expected.
I tried to open the feed this way :
URL feedUrl = new URL(address);
Inputstream iStream = feedURL.openStream();
//or
Inputstream iStream = (InputStream)feedURL.getContent();
So... Is there anyway other way to do it? Anyway to avoid this redirection? I have absolutely no control over the website...
Thanks everyone!
A:
What is probably happening is that the URL connection attaches a default user agent header to the HTTP request. The mobile web site receives this and redirects you to the mobile web site. I believe that it won't be possible to change this behaviour with Android's version of URL class.
A solution would be to use HttpClient, which you should be doing already anyhow.
| {
"pile_set_name": "StackExchange"
} |
Q:
.on('click') works and doesn't works (IE and Edge)
So i have an issue with the .on('click') on IE and Edge
This my code where the issue is :
$('.titleMarge').on('click',function(){
$('.margeConfig').css('display','block');
$('.borderDivConfig').css('display','none');
$('.shadowConfig').css('display','none');
$('.activeMarge').html('◄');
$('.activeBorder').html('');
$('.activeOmbre').html('');
});
$('.titleBorder').on('click',function(){
$('.borderDivConfig').css('display','block');
$('.margeConfig').css('display','none');
$('.shadowConfig').css('display','none');
$('.activeMarge').html('');
$('.activeBorder').html('◄');
$('.activeOmbre').html('');
});
$('.titleShadow').on('click',function(){
$('.shadowConfig').css('display','block');
$('.borderDivConfig').css('display','none');
$('.margeConfig').css('display','none');
$('.activeMarge').html('');
$('.activeBorder').html('');
$('.activeOmbre').html('◄');
});
On all other browsers, this works fine but on IE and Edge only the $('.titleBorder') doesn't work..
Any idea ?
A:
Oh my... I'm so stupid, I didn't know that IE and Edge are case sensitive.
I, accidentally, wrote <h3 class="TitleBorder"> with a 'T' instead of a 't' When testing my code on Chrome, Firefox , ... No errors and everything works fine So my guess is that IE and Edge are case sensitive Thanks everyone !
| {
"pile_set_name": "StackExchange"
} |
Q:
C# HTTP Reader get values from JSON format
I have a C# application getting a string from an HTTP listener. The data is sent to my application in the JSON format, and I am trying to get the specific values.
Right now, I read the data sent to me using:
HttpListenerContext context = listener.GetContext();
var request = context.Request;
string message;
using (var reader = new StreamReader(request.InputStream,
request.ContentEncoding))
{
message = reader.ReadToEnd();
}
The string message = { "message": "I've been shot!", "phoneNumber": "12345?", "position": "???", "anon": "???", "job": "ambulance" }
How would I go about getting these specific values and setting a string equal to the message, phonenumber, position, etc. Instead of just using the reader.ReadToEnd()
Thanks!
A:
Using Netwonsoft.Json, you can create an anonymous type to use as a template, then use the type to create an object with friendly property names. You even get intellisense!
Example of parsing your example object:
public static void Main()
{
string input = @"{ ""message"": ""I've been shot!"", ""phoneNumber"": ""12345?"", ""position"": ""???"", ""anon"": ""???"", ""job"": ""ambulance"" }";
var objectTemplate = new
{
message = "",
phoneNumber = "",
position = "",
anon = "",
job = ""
};
var deserialized = JsonConvert.DeserializeAnonymousType(input, objectTemplate);
Console.WriteLine(deserialized.message);
Console.WriteLine(deserialized.phoneNumber);
Console.WriteLine(deserialized.position);
}
Output:
I've been shot!
12345?
???
Code on DotNetFiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Do any Bibles contain the Book of Nathan the Prophet and/or the History of Nathan the Prophet
A possible reference to the Book of Nathan is described in 1 Chronicles 29:29:
"Now the acts of David the king, first and last, behold, they are written in the book of Samuel the seer, and in the book of Nathan the prophet, and in the book of Gad the seer."
A possible reference to the History of Nathan the Prophet is described in 2 Chronicles 9:29:
"Now the rest of the acts of Solomon, first and last, are they not written in the history of Nathan the prophet..."
I seek information on the whereabouts of these writings and whether they are considered to be authentic by either the Christian or Jewish religious community.
A:
It may be the views of Judaism on the matter of this ‘Book [or History] of Nathan’ that has given rise to questions about existence or authenticity. The Book of Nathan the Prophet and the History of Nathan the Prophet are among 19 “lost books of the Tanakh”. They may be the same text, but they are sometimes distinguished from one another. As no such text is found in the Tanakh, some assume that text has been lost or removed from earlier ones.
The Bible itself speaks of such prophets and their writings. There are two passages in the Old Testament that speak of them. First, there is 1 Chronicles 29:29 which goes up to the death of King David and mentions
“Samuel the seer, the records of Nathan the prophet and the records of
Gad the seer.”
Second, there is 2 Chronicles 9:29 which is about the reign of King Solomon:
“As for the other events of Solomon’s reign, from beginning to end,
are they not written in the records of Nathan the prophet, in the
prophecy of Ahijah the Shilonite and in the visions of Iddo the
seer..."
The Bible appears to says very little but elsewhere we find additional information that enables a complete picture to be put together.
The New International Study Bible (1987 edition) gives such helpful information in its ‘Author, Date and Sources’ section to the introduction of 1 Chronicles (page 566) that I now quote from it.
“According to ancient Jewish tradition, Ezra wrote Chronicles… but
this cannot be established with certainty… In his recounting of
history long past the Chronicler relied on many written sources. About
half his work was taken from Samuel and Kings; he also drew on the
Pentateuch, Judges, Ruth, Psalms, Isaiah, Jeremiah, Lamentations and
Zechariah… There are frequent references to yet other sources: ‘the
book of the kings of Israel’ (9:1; 2Ch 20:34; cf. 2Ch33:18), ‘the book
of the annals of King David’ (27:24), ‘the book of the kings of Judah
and Israel’ or ‘…of Israel and Judah’ (2Ch 16:11; 25:26; 27:7; 28:26;
32:32; 35:27; 36:8). ‘the annotations on the books of the kings’ (2Ch
24:27). It is unclear whether these all refer to the same source or to
different sources… In addition, the author cites a number of prophetic
writings: those of ‘Samuel the seer’ (29:29), ‘Nathan the prophet
(29:29 2Ch 9:29), ‘Gad the seer’ (29:29), ‘Ahijah the Shilonite’ (2Ch
9:29), ‘Iddo the seer’ (2Ch 9:29; 12:15; 13:22), ‘Shemaiah the prophet
(2Ch 12:15), ‘the prophet Isaiah’ (2Ch 26:22), ‘the seers’ (2Ch
33:19)… He did not invent, but he did select, arrange and integrate
his sources to compose a narrative ‘sermon’ for post-exilic Israel as
she struggled to find her bearings as the people of God in a new
situation.”
There is a need to see the book of Nathan the prophet, the book of Gad the seer and the history of Nathan the prophet in that context.
Now come the chronological factors. Please note that 1 Chronicles 29:29 also mentions “the records of Gad the seer” and his name crops up again in 1 Samuel 22:5 where we find that it is the prophet Gad, not Samuel, who gives instructions to David.
“But the prophet Gad said to David, ‘Do not stay in the stronghold. Go
into the land of Judah. So David left and went to the forest of
Hereth.”
That is significant because it was the prophet Samuel who had earlier anointed the boy David to be king (1 Samuel 16:1-13) but when Gad is mentioned David is still king-in-waiting as king Saul continues to reign. This is where a bit of chronology and age of the characters involved needs to be worked out.
Samuel was born in 1105 B.C. and he was an old man when he anointed Saul to be king (1 Samuel 8:1-5) and Saul reigned for 40 years from 1050 to 1010 B.C. (Acts 13:20-21). David reigned from 1010 to 970 B.C. This means that Samuel was 55 years old when Saul came to the throne and he would have been 95 years old if he had lived long enough to see David become king. But Samuel died long before then, while Saul was still alive and before David became king (1 Samuel 25:1).
Samuel anointed Saul then later God told Samuel to anoint David. However, it is the prophet Gad, not Samuel, who gave instructions to David to depart into the land of Judah (1 Samuel 22:5). That is because Samuel was a very old man. Likewise, it is Nathan who rebukes David after he takes Bathsheba to be his wife (2 Samuel 12:7-10). That is because Samuel had died.
Samuel lived long enough to anoint David to be king, but not long enough to see him sit upon the throne. Nathan and Gad took over from where Samuel left off. God used these men as his messengers and as his scribes. It is they who record the events of King David’s reign, from beginning to end. Their writings, their books, were never lost because they exist today within the books of Samuel and Chronicles. God used Samuel to write part of the history of Israel as the time of the judges was drawing to a close, and the time of the kings beginning; then God used men like Nathan and Gad to continue writing that history of God’s dealings with His people during the times of the kings. The writer of the Chronicles in the Old Testament drew upon those, and other sources, to make a comprehensive compilation of that history, to help the post-exilic Israelites.
In summary, the answer to your question is that the writings you ask about have been incorporated into the Old Testament itself, in various places as detailed above, so in that sense they have not been ‘lost’. The originals may have had more material but those originals are not available just as none of the original manuscripts of any and all of the Bible (the autographs) are not available. They are considered to be authentic, certainly by Christians, and to the extent that they are in the ancient Hebrew scriptures, Judaism also accepts them. All Bibles have Nathan’s writings as source material that has been incorporated into various parts of it, parts with other book names; it’s just that there is no ‘Book of Nathan’ on its own.
| {
"pile_set_name": "StackExchange"
} |
Q:
Could we abstract over type classes?
I wonder if ithere is a deeper reason that we cannot abstract over type classes (or can we?).
For example, when we have
fzip :: (forall a.[a] -> [a]) -> [b] -> [c] -> [(b,c)]
fzip f xs ys = zip (f xs) (f ys)
then we can say
fzip (drop 42) [1..100] ['a'..'z']
fzip reverse [1..100] ['a'..'z']
and so on. But we cannot
fzip (map succ) [1..100] ['a'..'z']
which we can fix with:
ezip :: (Enum b, Enum c) => (forall a.Enum a => [a] -> [a]) -> [b] -> [c] -> [(b,c)]
ezip f xs ys = zip (f xs) (f ys)
and likewise we can fix
fzip (map (5*)) [1..100] [1.5, 2.3, 4.7]
with
nzip :: (Num b, Num c) => (forall a.Num a => [a] -> [a]) -> [b] -> [c] -> [(b,c)]
nzip f xs ys = zip (f xs) (f ys)
But is it not embarassing that we cannot subsume ezip and nzip with something like:
gzip :: (g b, g c) => (forall a. g a => [a] -> [a]) -> [b] -> [c] -> [(b,c)]
though the code is absolutly identical, up to the name of the class?
Or can we somehow?
Interestingly, when instances were just records that contained functions, this would be easily possible.
A:
You can almost do this with ConstraintKinds:
{-# LANGUAGE ConstraintKinds, RankNTypes #-}
import Data.Proxy
gzip :: (g b, g c) => Proxy g -> (forall a . g a => [a] -> [a]) -> [b] -> [c] -> [(b,c)]
gzip _ f xs ys = zip (f xs) (f ys)
test1 = gzip (Proxy :: Proxy Enum) (map succ) [1 .. 100] ['a' .. 'z']
test2 = gzip (Proxy :: Proxy Num) (map (5*)) [1 .. 100] [1.5, 2.3, 4.7]
The main difference is that you need the Proxy argument, because GHC is unable to infer the right instantiation for g without help.
A:
Add a Proxy argument for the constraint:
{-# LANGUAGE PartialTypeSignatures #-}
import Data.Proxy
gzip :: (g b, g c) => Proxy g -> (forall a. g a => [a] -> [a]) -> [b] -> [c] -> [(b,c)]
gzip _ f bs cs = zip (f bs) (f cs)
> gzip (Proxy :: _ Enum) [0, 1] "ab"
[(1,'b'),(2,'c')]
GHC considers constraint parameters that only occur in constraints ambiguous, so we need to record them explicitly in a Proxy.
| {
"pile_set_name": "StackExchange"
} |
Q:
TextToSpeech in a Service
I've got a problem with TTS in a Service. It acts like it wants to talk but it never does. Watching the LogCat it prints "TTS received: the text it should speak" and I Log when it init's and that's showing success. I've tried creating a thread for it, that didnt help.
onUtteranceComplete never triggers either. I've even done a while loop like this (just for testing):
while(mTTS.isSpeaking()) {
Log.d("", "speaking");
}
...and it's never speaking
I know TTS is setup correctly because it works in a regular Activity
Here's my code.
import java.util.HashMap;
import java.util.Locale;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
public class TTSService extends Service implements OnInitListener, OnUtteranceCompletedListener {
TextToSpeech mTTS;
@Override
public void onCreate() {
Log.d("", "TTSService Created!");
mTTS = new TextToSpeech(getApplicationContext(), this);
//I've tried it in a thread....
/*new Thread(new Runnable() {
@Override
public void run() {
HashMap<String, String> myHashStream = new HashMap<String, String>();
myHashStream.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
myHashStream.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "1");
mTTS.setLanguage(Locale.US);
//mTTS.setOnUtteranceCompletedListener(this);
mTTS.speak("I'm saying some stuff to you!", TextToSpeech.QUEUE_FLUSH, myHashStream);
}
}).start();*/
//I've tried it not in a thread...
HashMap<String, String> myHashStream = new HashMap<String, String>();
myHashStream.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
myHashStream.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "1");
mTTS.setLanguage(Locale.US);
mTTS.setOnUtteranceCompletedListener(this);
mTTS.speak("I'm saying some stuff to you!", TextToSpeech.QUEUE_FLUSH, myHashStream);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onInit(int status) {
Log.d("", "TTSService onInit: " + String.valueOf(status));
if(status == TextToSpeech.SUCCESS){
Log.d("", "TTS Success");
}
}
public void onUtteranceCompleted(String uttId) {
Log.d("", "done uttering");
if(uttId == "1") {
mTTS.shutdown();
}
}
}
Thanks
A:
Ok, I've got it figured out now! What was happening is it was trying to speak before TTS was initialized. So in a thread I wait for ready to not == 999. Once its either 1 or anything else we'll then take care of speaking. This might not be safe putting it in a while loop but... It's working nonetheless.
import java.util.HashMap;
import java.util.Locale;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
public class TTSService extends Service implements OnInitListener, OnUtteranceCompletedListener {
TextToSpeech mTTS;
int ready = 999;
@Override
public void onCreate() {
Log.d("", "TTSService Created!");
mTTS = new TextToSpeech(getApplicationContext(), this);
new Thread(new Runnable() {
@Override
public void run() {
while(ready == 999) {
//wait
}
if(ready==1){
HashMap<String, String> myHashStream = new HashMap<String, String>();
myHashStream.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
myHashStream.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "1");
mTTS.setLanguage(Locale.US);
//mTTS.setOnUtteranceCompletedListener(this);
mTTS.speak("I'm saying some stuff to you!", TextToSpeech.QUEUE_FLUSH, myHashStream);
} else {
Log.d("", "not ready");
}
}
}).start();
stopSelf();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
mTTS.shutdown();
super.onDestroy();
}
@Override
public void onInit(int status) {
Log.d("", "TTSService onInit: " + String.valueOf(status));
if (status == TextToSpeech.SUCCESS)
{
ready = 1;
} else {
ready = 0;
Log.d("", "failed to initialize");
}
}
public void onUtteranceCompleted(String uttId) {
Log.d("", "done uttering");
if(uttId == "1") {
mTTS.shutdown();
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ReSharper Shift+Alt+L (go to open file) not working in 2015 with .resx?
I'm wondering if this is just my ReSharper setup, but as of updating to Visual Studio 2015 with ReSharper Ultimate 9.1.3, using the Shift+Alt+L shortcut while editing a .resx in the designer does nothing.
Has anybody else experienced this, and is there any config that will get this working or is it a bug?
Thanks
A:
This was caused (for me anyway) because my keyboard mapping had magically changed back to UK mapping from US (I want US).
The other day I had another issue that caused Resharper key mappings to go awry and followed some advice on another post (I can't find it at the moment) that want along the lines of:
Open Tools > Options > Keyboard and hit Reset
Open Resharper > Options > Keyboard & Menus, select "Visual Studio" and hit "Apply Scheme"
This should wrest control from Resharper back to Visual Studio and give Resharper the freedom it needs to wrest control back from VS.. ugh, but it worked
A:
Maybe have a look to Stackoverflow - How to locate a file in Solution Explorer in Visual Studio 2010?.
Tools (in Menu) -> Options -> Keyboard -> goto input Show commands containing and type SolutionExplorer.SyncWithActiveDocument. Goto Press Shortcut Keys and press Shift + Alt + L click on Assign button.
You may get a warning that the shortcut is already in use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Use Python to Accumulate Values in Certain Columns with Timestamp Basis?
I have a large text file, looks like in the following format:
89703 71.839532000 192.168.0.24 10.0.0.5 52222 5201 1514 1500 1448
89704 71.840310000 192.168.0.24 10.0.0.5 52222 5201 1514 1500 1448
89707 71.902452000 192.168.0.24 10.0.0.5 52222 5201 1514 1500 1448
89708 71.943320000 192.168.0.24 10.0.0.5 52222 5201 1514 1500 1448
89720 72.050930000 192.168.0.24 10.0.0.5 52222 5201 1514 1500 1448
89722 72.051725000 192.168.0.24 10.0.0.5 52222 5201 1514 1500 1448
89723 72.067882000 192.168.0.24 10.0.0.5 52222 5201 1514 1500 1448
89724 72.153261000 192.168.0.24 10.0.0.5 52222 5201 1514 1500 1448
89725 72.290161000 192.168.0.24 10.0.0.5 52222 5201 0
The second column means timestamp (e.g. 71.839532000 second), the sixth to eighth columns are the data output which was happened at that time.
I want to write a script to calculate how much data has been used in every 0.1 second period for the sixth column to the eighth column. For example, from 71.80000s to 71.899999s, the total value of the sixth, seventh and eighth column is 3028 (1514+1514), 3000 (1500+1500) and 2896 (1448+1448) respectively.
The output will look something like that:
71.8 3028 3000 2896
71.9 3028 3000 2896
72.0 4512 4500 4344
72.1 1514 1500 1448
72.2 0 0 0
How to achieve it with python? If it is not achievable, what language can we use?
A:
First I converted your sample data to csv just to make it easier to deal with. (You can still use tab separation but I think it converted it to spaces in stack overflow)
I also added a header
a,timestamp,ip,ip2,b,c,data,d,e
89703,71.839532000,192.168.0.24,10.0.0.5,52222,5201,1514,1500,1448
89704,71.840310000,192.168.0.24,10.0.0.5,52222,5201,1514,1500,1448
89707,71.902452000,192.168.0.24,10.0.0.5,52222,5201,1514,1500,1448
89708,71.943320000,192.168.0.24,10.0.0.5,52222,5201,1514,1500,1448
89720,72.050930000,192.168.0.24,10.0.0.5,52222,5201,1514,1500,1448
89722,72.051725000,192.168.0.24,10.0.0.5,52222,5201,1514,1500,1448
89723,72.067882000,192.168.0.24,10.0.0.5,52222,5201,1514,1500,1448
89724,72.153261000,192.168.0.24,10.0.0.5,52222,5201,1514,1500,1448
89725,72.290161000,192.168.0.24,10.0.0.5,52222,5201,0
Then I used pandas, which is a popular data processing library in python.
read the data as a csv
convert the timestamp column from number (float) to timestamp (datetime)
group by timestamps 100 microseconds (0.1 seconds), sum, and select data column
import pandas as pd
data = pd.read_csv("sample_data.tsv")
data.timestamp = pd.to_datetime(data.timestamp, unit='ms')
data.groupby(pd.Grouper(key='timestamp', freq='100U')).sum()["data"]
Output
timestamp
1970-01-01 00:00:00.071800 3028
1970-01-01 00:00:00.071900 3028
1970-01-01 00:00:00.072000 4542
1970-01-01 00:00:00.072100 1514
1970-01-01 00:00:00.072200 0
The other data is there too.
>>> data.groupby(pd.Grouper(key='timestamp', freq='100U')).sum()
a b c data d e
timestamp
1970-01-01 00:00:00.071800 179407 104444 10402 3028 3000.0 2896.0
1970-01-01 00:00:00.071900 179415 104444 10402 3028 3000.0 2896.0
1970-01-01 00:00:00.072000 269165 156666 15603 4542 4500.0 4344.0
1970-01-01 00:00:00.072100 89724 52222 5201 1514 1500.0 1448.0
1970-01-01 00:00:00.072200 89725 52222 5201 0 0.0 0.0
This can be written to csv using pandas as well.
Edit: I had the variable name a when coding up the snippet, then changed it to data when posting.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the current status of handwriting recognition on the iPad with an air pencil or stylus
Ideally I want to be able to use my ipad as a clipboard running google sheets to do inventory entry. So I'm looking for a general purpose stylus to text converter.
Seems strange that Palm got this pretty close to right 20 years ago, but there is little progress since.
Research into this found a flurry of articles written shortly after the air pencil came out, but I've found little since then. So my current answer is, "Moribund"
A:
iOS currently doesn't support handwriting recognition on OS level. There are apps for the Pro models (with Apple Pencil) that recognize handwriting, but this won't help you with Google Sheets or similar.
Things appear to be more bright with iOS 14 (the version to be released later in 2020). Apple will introduce handwriting recognition on OS level, at least for the Pro models, with a feature called Scribble. Check out https://www.apple.com/ipados/ipados-preview/ for the details already known.
| {
"pile_set_name": "StackExchange"
} |
Q:
How does IPv4 Subnetting Work?
This is a Canonical Question about IPv4 Subnets.
Related:
How does IPv6 subnetting work and how does it differ from IPv4 subnetting?
How does Subnetting Work, and How do you do it by hand or in your head? Can someone explain both conceptually and with several examples? Server Fault gets lots of subnetting homework questions, so we could use an answer to point them to on Server Fault itself.
If I have a network, how do I figure
out how to split it up?
If I am given a netmask, how do I
know what the network Range is for
it?
Sometimes there is a slash followed
by a number, what is that number?
Sometimes there is a subnet mask, but also a wildcard mask, they seem like the same thing but they are different?
Someone mentioned something about knowing binary for this?
A:
IP subnets exist to allow routers to choose appropriate destinations for packets. You can use IP subnets to break up larger networks for logical reasons (firewalling, etc), or physical need (smaller broadcast domains, etc).
Simply put, though, IP routers use your IP subnets to make routing decisions. Understand how those decisions work, and you can understand how to plan IP subnets.
Counting to 1
If you are already fluent in binary (base 2) notation you can skip this section.
For those of you who are left: Shame on you for not being fluent in binary notation!
Yes, that may be a bit harsh. It's really, really easy to learn to count in binary, and to learn shortcuts to convert binary to decimal and back. You really should know how to do it.
Counting in binary is so simple because you only have to know how to count to 1!
Think of a car's "odometer", except that unlike a traditional odometer each digit can only count up to 1 from 0. When the car is fresh from the factory the odometer reads "00000000".
When you've driven your first mile the odometer reads "00000001". So far, so good.
When you've driven your second mile the first digit of the odometer rolls back over to "0" (since its maximum value is "1") and the second digit of the odometer rolls over to "1", making the odometer read "00000010". This looks like the number 10 in decimal notation, but it's actually 2 (the number of miles you've driven the car so far) in binary notation.
When you've driven the third mile the odometer reads "00000011", since the first digit of the odometer turns again. The number "11", in binary notation, is the same as the decimal number 3.
Finally, when you've driven your fourth mile both digits (which were reading "1" at the end of the third mile) roll back over to zero position, and the 3rd digit rolls up to the "1" position, giving us "00000100". That's the binary representation of the decimal number 4.
You can memorize all of that if you want, but you really only need to understand how the little odometer "rolls over" as the number it's counting gets bigger. It's exactly the same as a traditional decimal odometer's operation, except that each digit can only be "0" or "1" on our fictional "binary odometer".
To convert a decimal number to binary you could roll the odometer forward, tick by tick, counting aloud until you've rolled it a number of times equal to the decimal number you want to convert to binary. Whatever is displayed on the odometer after all that counting and rolling would be the binary representation of the decimal number you counted up to.
Since you understand how the odometer rolls forward you'll also understand how it rolls backward, too. To convert a binary number displayed on the odometer back to decimal you could roll the odometer back one tick at a time, counting aloud until the odometer reads "00000000". When all that counting and rolling is done, the last number you say aloud would be the decimal representation of the binary number the odometer started with.
Converting values between binary and decimal this way would be very tedious. You could do it, but it wouldn't be very efficient. It's easier to learn a little algorithm to do it faster.
A quick aside: Each digit in a binary number is known as a "bit". That's "b" from "binary" and "it" from "digit". A bit is a bnary digit.
Converting a binary number like, say, "1101011" to decimal is a simple process with a handy little algorithm.
Start by counting the number of bits in the binary number. In this case, there are 7. Make 7 divisions on a sheet of paper (in your mind, in a text file, etc) and begin filling them in from right to left. In the rightmost slot, enter the number "1", because we'll always start with "1". In the next slot to the left enter double the value in the slot to the right (so, "2" in the next one, "4" in the next one) and continue until all the slots are full. (You'll end up memorizing these numbers, which are the powers of 2, as you do this more and more. I'm alright up to 131,072 in my head but I usually need a calculator or paper after that).
So, you should have the following on your paper in your little slots.
64 | 32 | 16 | 8 | 4 | 2 | 1 |
Transcribe the bits from the binary number below the slots, like so:
64 | 32 | 16 | 8 | 4 | 2 | 1 |
1 1 0 1 0 1 1
Now, add some symbols and compute the answer to the problem:
64 | 32 | 16 | 8 | 4 | 2 | 1 |
x 1 x 1 x 0 x 1 x 0 x 1 x 1
--- --- --- --- --- --- ---
+ + + + + + =
Doing all the math, you should come up with:
64 | 32 | 16 | 8 | 4 | 2 | 1 |
x 1 x 1 x 0 x 1 x 0 x 1 x 1
--- --- --- --- --- --- ---
64 + 32 + 0 + 8 + 0 + 2 + 1 = 107
That's got it. "1101011" in decimal is 107. It's just simple steps and easy math.
Converting decimal to binary is just as easy and is the same basic algorithm, run in reverse.
Say that we want to convert the number 218 to binary. Starting on the right of a sheet of paper, write the number "1". To the left, double that value (so, "2") and continue moving toward the left of the paper doubling the last value. If the number you are about to write is greater than the number being converted stop writing. otherwise, continue doubling the prior number and writing. (Converting a big number, like 34,157,216,092, to binary using this algorithm can be a bit tedious but it's certainly possible.)
So, you should have on your paper:
128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
You stopped writing numbers at 128 because doubling 128, which would give you 256, would be large than the number being converted (218).
Beginning from the leftmost number, write "218" above it (128) and ask yourself: "Is 218 larger than or equal to 128?" If the answer is yes, scratch a "1" below "128". Above "64", write the result of 218 minus 128 (90).
Looking at "64", ask yourself: "Is 90 larger than or equal to 64?" It is, so you'd write a "1" below "64", then subtract 64 from 90 and write that above "32" (26).
When you get to "32", though, you find that 32 is not greater than or equal to 26. In this case, write a "0" below "32", copy the number (26) from above 32" to above "16" and then continue asking yourself the same question with the rest of the numbers.
When you're all done, you should have:
218 90 26 26 10 2 2 0
128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
1 1 0 1 1 0 1 0
The numbers at the top are just notes used in computation and don't mean much to us. At the bottom, though, you see a binary number "11011010". Sure enough, 218, converted to binary, is "11011010".
Following these very simple procedures you can convert binary to decimal and back again w/o a calculator. The math is all very simple and the rules can be memorized with just a bit of practice.
Splitting Up Addresses
Think of IP routing like pizza delivery.
When you're asked to deliver a pizza to "123 Main Street" it's very clear to you, as a human, that you want to go to the building numbered "123" on the street named "Main Street". It's easy to know that you need to go to the 100-block of Main Street because the building number is between 100 and 199 and most city blocks are numbered in hundreds. You "just know" how to split the address up.
Routers deliver packets, not pizza. Their job is the same as a pizza driver: To get the cargo (packets) as close to the destination as possible. A router is connected to two or more IP subnets (to be at all useful). A router must examine destination IP addresses of packets and break those destination addresses up into their "street name" and "building number" components, just like the pizza driver, to make decisions about delivery.
Each computer (or "host") on an IP network is configured with a unique IP address and subnet mask. That IP address can be divided up into a "building number" component (like "123" in the example above) called the "host ID" and a "street name" component (like "Main Street" in the example above) called the "network ID". For our human eyes, it's easy to see where the building number and the street name are in "123 Main Street", but harder to see that division in "10.13.216.41 with a subnet mask of 255.255.192.0".
IP routers "just know" how to split up IP addresses into these component parts to make routing decisions. Since understanding how IP packets are routed hinges on understanding this process, we need to know how to break up IP addresses, too. Fortunately, extracting the host ID and the network ID out of an IP address and subnet mask is actually pretty easy.
Start by writing out the IP address in binary (use a calculator if you haven't learned to do this in your head just yet, but make a note learn how to do it-- it's really, really easy and impresses the opposite sex at parties):
10. 13. 216. 41
00001010.00001101.11011000.00101001
Write out the subnet mask in binary, too:
255. 255. 192. 0
11111111.11111111.11000000.00000000
Written side-by-side, you can see that the point in the subnet mask where the "1s" stop "lines up" to a point in the IP address. That's the point that the network ID and the host ID split. So, in this case:
10. 13. 216. 41
00001010.00001101.11011000.00101001 - IP address
11111111.11111111.11000000.00000000 - subnet mask
00001010.00001101.11000000.00000000 - Portion of IP address covered by 1s in subnet mask, remaining bits set to 0
00000000.00000000.00011000.00101001 - Portion of IP address covered by 0s in subnet mask, remaining bits set to 0
Routers use the subnet mask to "mask out" the bits covered by 1s in the IP address (replacing the bits that are not "masked out" with 0s) to extract the network ID:
10. 13. 192. 0
00001010.00001101.11000000.00000000 - Network ID
Likewise, by using the subnet mask to "mask out" the bits covered by 0s in the IP address (replacing the bits that are not "masked out" with 0s again) a router can extract the host ID:
0. 0. 24. 41
00000000.00000000.00011000.00101001 - Portion of IP address covered by 0s in subnet mask, remaining bits set to 0
It's not as easy for our human eyes to see the "break" between the network ID and the host ID as it is between the "building number" and the "street name" in physical addresses during pizza delivery, but the ultimate effect is the same.
Now that you can split up IP addresses and subnet masks into host ID's and network ID's you can route IP just like a router does.
More Terminology
You're going to see subnet masks written all over the Internet and throughout the rest of this answer as (IP/number). This notation is known as "Classless Inter-Domain Routing" (CIDR) notation. "255.255.255.0" is made up of 24 bits of 1s at the beginning, and it's faster to write that as "/24" than as "255.255.255.0". To convert a CIDR number (like "/16") to a dotted-decimal subnet mask just write out that number of 1s, split it into groups of 8 bits, and convert it to decimal. (A "/16" is "255.255.0.0", for instance.)
Back in the "old days", subnet masks weren't specified, but rather were derived by looking at certain bits of the IP address. An IP address starting with 0 - 127, for example, had an implied subnet mask of 255.0.0.0 (called a "class A" IP address).
These implied subnet masks aren't used today and I don't recommend learning about them anymore unless you have the misfortune of dealing with very old equipment or old protocols (like RIPv1) that don't support classless IP addressing. I'm not going to mention these "classes" of addresses further because it's inapplicable today and can be confusing.
Some devices use a notation called "wildcard masks". A "wildcard mask" is nothing more than a subnet mask with all 0s where there would be 1s, and 1s where there would be 0s. The "wildcard mask" of a /26 is:
11111111.11111111.11111111.11000000 - /26 subnet mask
00000000.00000000.00000000.00111111 - /26 "wildcard mask"
Typically you see "wildcard masks" used to match host IDs in access-control lists or firewall rules. We won't discuss them any further here.
How a Router Works
As I've said before, IP routers have a similar job to a pizza delivery driver in that they need to get their cargo (packets) to its destination. When presented with a packet bound for address 192.168.10.2, an IP router needs to determine which of its network interfaces will best get that packet closer to its destination.
Let's say that you are an IP router, and you have interfaces connected to you numbered:
Ethernet0 - 192.168.20.1, subnet mask /24
Ethernet1 - 192.168.10.1, subnet mask /24
If you receive a packet to deliver with a destination address of "192.168.10.2", it's pretty easy to tell (with your human eyes) that the packet should be sent out the interface Ethernet1, because the Ethernet1 interface address corresponds to the packet's destination address. All the computers attached to the Ethernet1 interface will have IP addresses starting with "192.168.10.", because the network ID of the IP address assigned to your interface Ethernet1 is "192.168.10.0".
For a router, this route selection process is done by building a routing table and consulting the table each time a packet is to be delivered. A routing table contains network ID and destination interface names. You already know how to obtain a network ID from an IP address and subnet mask, so you're on your way to building a routing table. Here's our routing table for this router:
Network ID: 192.168.20.0 (11000000.10101000.00010100.00000000) - 24 bit subnet mask - Interface Ethernet0
Network ID: 192.168.10.0 (11000000.10101000.00001010.00000000) - 24 bit subnet mask - Interface Ethernet1
For our incoming packet bound for "192.168.10.2", we need only convert that packet's address to binary (as humans -- the router gets it as binary off the wire to begin with) and attempt to match it to each address in our routing table (up to the number of bits in the subnet mask) until we match an entry.
Incoming packet destination: 11000000.10101000.00001010.00000010
Comparing that to the entries in our routing table:
11000000.10101000.00001010.00000010 - Destination address for packet
11000000.10101000.00010100.00000000 - Interface Ethernet0
!!!!!!!!.!!!!!!!!.!!!????!.xxxxxxxx - ! indicates matched digits, ? indicates no match, x indicates not checked (beyond subnet mask)
11000000.10101000.00001010.00000010 - Destination address for packet
11000000.10101000.00001010.00000000 - Interface Ethernet1, 24 bit subnet mask
!!!!!!!!.!!!!!!!!.!!!!!!!!.xxxxxxxx - ! indicates matched digits, ? indicates no match, x indicates not checked (beyond subnet mask)
The entry for Ethernet0 matches the first 19 bits fine, but then stops matching. That means it's not the proper destination interface. You can see that the interface Ethernet1 matches 24 bits of the destination address. Ah, ha! The packet is bound for interface Ethernet1.
In a real-life router, the routing table is sorted in such a manner that the longest subnet masks are checked for matches first (i.e. the most specific routes), and numerically so that as soon as a match is found the packet can be routed and no further matching attempts are necessary (meaning that 192.168.10.0 would be listed first and 192.168.20.0 would never have been checked). Here, we're simplifying that a bit. Fancy data structures and algorithms make faster IP routers, but simple algorithms will produce the same results.
Static Routes
Up to this point, we've talked about our hypothetical router as having networks directly connected to it. That's not, obviously, how the world really works. In the pizza-driving analogy, sometimes the driver isn't allowed any further into the building than the front desk, and has to hand-off the pizza to somebody else for delivery to the final recipient (suspend your disbelief and bear with me while I stretch my analogy, please).
Let's start by calling our router from the earlier examples "Router A". You already know RouterA's routing table as:
Network ID: 192.168.20.0 (11000000.10101000.00010100.00000000) - subnet mask /24 - Interface RouterA-Ethernet0
Network ID: 192.168.10.0 (11000000.10101000.00001010.00000000) - subnet mask /24 - Interface RouterA-Ethernet1
Suppose that there's another router, "Router B", with the IP addresses 192.168.10.254/24 and 192.168.30.1/24 assigned to its Ethernet0 and Ethernet1 interfaces. It has the following routing table:
Network ID: 192.168.10.0 (11000000.10101000.00001010.00000000) - subnet mask /24 - Interface RouterB-Ethernet0
Network ID: 192.168.30.0 (11000000.10101000.00011110.00000000) - subnet mask /24 - Interface RouterB-Ethernet1
In pretty ASCII art, the network looks like this:
Interface Interface
Ethernet1 Ethernet1
192.168.10.1/24 192.168.30.254/24
__________ V __________ V
| | V | | V
----| ROUTER A |------- /// -------| ROUTER B |----
^ |__________| ^ |__________|
^ ^
Interface Interface
Ethernet0 Ethernet0
192.168.20.1/24 192.168.10.254/24
You can see that Router B knows how to "get to" a network, 192.168.30.0/24, that Router A knows nothing about.
Suppose that a PC with the IP address 192.168.20.13 attached to the network connected to router A's Ethernet0 interface sends a packet to Router A for delivery. Our hypothetical packet is destined for the IP address 192.168.30.46, which is a device attached to the network connected to the Ethernet1 interface of Router B.
With the routing table shown above, neither entry in Router A's routing table matches the destination 192.168.30.46, so Router A will return the packet to the sending PC with the message "Destination network unreachable".
To make Router A "aware" of the existence of the 192.168.30.0/24 network, we add the following entry to the routing table on Router A:
Network ID: 192.168.30.0 (11000000.10101000.00011110.00000000) - subnet mask /24 - Accessible via 192.168.10.254
In this way, Router A has a routing table entry that matches the 192.168.30.46 destination of our example packet. This routing table entry effectively says "If you get a packet bound for 192.168.30.0/24, send it on to 192.168.10.254 because he knows how to deal with it." This is the analogous "hand-off the pizza at the front desk" action that I mentioned earlier-- passing the packet on to somebody else who knows how to get it closer to its destination.
Adding an entry to a routing table "by hand" is known as adding a "static route".
If Router B wants to deliver packets to the 192.168.20.0 subnet mask 255.255.255.0 network, it will need an entry in its routing table, too:
Network ID: 192.168.20.0 (11000000.10101000.00010100.00000000) - subnet mask /24 - Accessible via: 192.168.10.1 (Router A's IP address in the 192.168.10.0 network)
This would create a path for delivery between the 192.168.30.0/24 network and the 192.168.20.0/24 network across the 192.168.10.0/24 network between these routers.
You always want to be sure that routers on both sides of such an "interstitial network" have a routing table entry for the "far end" network. If router B in our example didn't have a routing table entry for "far end" network 192.168.20.0/24 attached to router A our hypothetical packet from the PC at 192.168.20.13 would get to the destination device at 192.168.30.46, but any reply that 192.168.30.46 tried to send back would be returned by router B as "Destination network unreachable." One-way communication is generally not desirable. Always be sure you think about traffic flowing in both directions when you think about communication in computer networks.
You can get a lot of mileage out of static routes. Dynamic routing protocols like EIGRP, RIP, etc, are really nothing more than a way for routers to exchange routing information between each other that could, in fact, be configured with static routes. One large advantage to using dynamic routing protocols over static routes, though, is that dynamic routing protocols can dynamically change the routing table based on network conditions (bandwidth utilization, an interface "going down", etc) and, as such, using a dynamic routing protocol can result in a configuration that "routes around" failures or bottlenecks in the network infrastructure. (Dynamic routing protocols are WAY outside the scope of this answer, though.)
You Can't Get There From Here
In the case of our example Router A, what happens when a packet bound for "172.16.31.92" comes in?
Looking at the Router A routing table, neither destination interface or static route matches the first 24 bits of 172.18.31.92 (which is 10101100.00010010.00011111.01011100, by the way).
As we already know, Router A would return the packet to the sender via a "Destination network unreachable" message.
Say that there's another router (Router C) sitting at the address "192.168.20.254". Router C has a connection to the Internet!
Interface Interface Interface
Ethernet1 Ethernet1 Ethernet1
192.168.20.254/24 192.168.10.1/24 192.168.30.254/24
__________ V __________ V __________ V
(( heap o )) | | V | | V | | V
(( internet )) ----| ROUTER C |------- /// -------| ROUTER A |------- /// -------| ROUTER B |----
(( w00t! )) ^ |__________| ^ |__________| ^ |__________|
^ ^ ^
Interface Interface Interface
Ethernet0 Ethernet0 Ethernet0
10.35.1.1/30 192.168.20.1/24 192.168.10.254/24
It would be nice if Router A could route packets that do not match any local interface up to Router C such that Router C can send them on to the Internet. Enter the "default gateway" route.
Add an entry at the end of our routing table like this:
Network ID: 0.0.0.0 (00000000.00000000.00000000.00000000) - subnet mask /0 - Destination router: 192.168.20.254
When we attempt to match "172.16.31.92" to each entry in the routing table we end up hitting this new entry. It's a bit perplexing, at first. We're looking to match zero bits of the destination address with... wait... what? Matching zero bits? So, we're not looking for a match at all. This routing table entry is saying, basically, "If you get here, rather than giving up on delivery, send the packet on to the router at 192.168.20.254 and let him handle it".
192.168.20.254 is a destination we DO know how to deliver a packet to. When confronted with a packet bound for a destination for which we have no specific routing table entry this "default gateway" entry will always match (since it matches zero bits of the destination address) and gives us a "last resort" place that we can send packets for delivery. You'll sometimes hear the default gateway called the "gateway of last resort."
In order for a default gateway route to be effective it must refer to a router that is reachable using the other entries in the routing table. If you tried to specify a default gateway of 192.168.50.254 in Router A, for example, delivery to such a default gateway would fail. 192.168.50.254 isn't an address that Router A knows how to deliver packets to using any of the other routes in its routing table, so such an address would be ineffective as a default gateway. This can be stated concisely: The default gateway must be set to an address already reachable by using another route in the routing table.
Real routers typically store the default gateway as the last route in their routing table such that it matches packets after they've failed to match all other entries in the table.
Urban Planning and IP Routing
Breaking up a IP subnet into smaller IP subnets is like urban planning. In urban planning, zoning is used to adapt to natural features of the landscape (rivers, lakes, etc), to influence traffic flows between different parts of the city, and to segregate different types of land-use (industrial, residential, etc). IP subnetting is really much the same.
There are three main reasons why you would subnet a network:
You may want to communicate across different unlike communication media. If you have a T1 WAN connection between two buildings IP routers could be placed on the ends of these connections to facilitate communication across the T1. The networks on each end (and possibly the "interstitial" network on the T1 itself) would be assigned to unique IP subnets so that the routers can make decisions about which traffic should be sent across the T1 line.
In an Ethernet network, you might use subnetting to limit the amount of broadcast traffic in a given portion of the network. Application-layer protocols use the broadcast capability of Ethernet for very useful purposes. As you get more and more hosts packed into the same Ethernet network, though, the percentage of broadcast traffic on the wire (or air, in wireless Ethernet) can increase to such a point as to create problems for delivery of non-broadcast traffic. (In the olden days, broadcast traffic could overwhelm the CPU of hosts by forcing them to examine each broadcast packet. That's less likely today.) Excessive traffic on switched Ethernet can also come in form of "flooding of frames to unknown destinations". This condition is caused by an Ethernet switch being unable to keep track of every destination on the network and is the reason why switched Ethernet networks can't scale to an infinite number of hosts. The effect of flooding of frames to unknown destinations is similar to the the effect of excess broadcast traffic, for the purposes of subnetting.
You may want to "police" the types of traffic flowing between different groups of hosts. Perhaps you have print server devices and you only want authorized print queuing server computers to send jobs to them. By limiting the traffic allowed to flow to the print server device subnet users can't configure their PCs to talk directly to the print server devices to bypass print accounting. You might put the print server devices into a subnet all to themselves and create a rule in the router or firewall attached to that subnet to control the list of hosts permitted to send traffic to the print server devices. (Both routers and firewalls can typically make decisions about how or whether to deliver a packet based on the source and destination addresses of the packet. Firewalls are typically a sub-species of router with an obsessive personality. They can be very, very concerned about the payload of packets, whereas routers typically disregard payloads and just deliver the packets.)
In planning a city, you can plan how streets intersect with each other, and can use turn-only, one-way, and dead-end streets to influence traffic flows. You might want Main Street to be 30 blocks long, with each block having up to 99 buildings each. It's pretty easy to plan your street numbering such that each block in Main Street has a range of street numbers increasing by 100 for each block. It's very easy to know what the "starting number" in each subsequent block should be.
In planning IP subnets, you're concerned with building the right number of subnets (streets) with the right number of available host ID's (building numbers), and using routers to connect the subnets to each other (intersections). Rules about allowed source and destination addresses specified in the routers can further control the flow of traffic. Firewalls can act like obsessive traffic cops.
For the purposes of this answer, building our subnets is our only major concern. Instead of working in decimal, as you would with urban planning, you work in binary to describe the bounds of each subnet.
Continued on: How does IPv4 Subnetting Work?
(Yes ... we reached the maximum size of an answer (30000 characters).)
A:
Continued from: How does IPv4 Subnetting Work?
Your ISP gives you the range the network ID 192.168.40.0/24 (11000000.10101000.00101000.00000000). You know that you'd like to use a firewall / router device to limit communication between different parts of your network (servers, client computers, network equipment) and, as such,you'd like to break these various parts of your network up into IP subnets (which the firewall / router device can then route between).
You have:
12 server computers, but you might get up to 50% more
9 switches
97 client computers, but you might get more
What's a good way to break up 192.168.40.0/24 into these pieces?
Thinking in even powers of two, and working with the larger numbers of possible devices, you can come up with:
18 server computers - Next largest power of two is 32
9 switches - Next largest power of two is 16
97 client computers - Next largest power of two is 128
In a given IP subnet, there are two addresses reserved that can't be used as valid device IP addresses-- the address with all zeros in the host ID portion and the address with all ones in the host ID portion. As such, for any given IP subnet, the number of host addresses available is two to the power of the quantity of 32 minus the number of bits in the subnet mask, minus 2. So, in the case of 192.168.40.0/24 we can see that the subnet mask has 24 bits. That leaves 8 bits available for host IDs. We know that 2 to the 8th power is 256-- meaning that 256 possible combinations of bits fit into a slot 8 bits wide. Since the "11111111" and "00000000" combinations of those 8 bits aren't allowable for host IDs, that leaves us with 254 possible hosts that can be assigned in the 192.168.40.0/24 network.
Of those 254 hosts, it looks like we can fit the client computers, switches, and server computers into that space, right? Let's try.
You have 8 bits of subnet mask to "play with" (the remaining 8 bits of the IP address 192.168.40.0/24 not covered by the subnet mask provided by your ISP). We have to work out a way to use those 8 bits to create a number of unique network IDs that can accommodate the devices above.
Start with the largest network - the client computers. You know that the next larger power of two from the number of possible devices is 128. The number 128, in binary, is "10000000". Fortunately for us, that fits into the 8 bit slot we have free (if it didn't, that would be an indication that our starting subnet is too small to accommodate all our devices).
Let's take our network ID, as provided by our ISP, and add a single bit of subnet mask to it, breaking it up into two networks:
11000000.10101000.00101000.00000000 - 192.168.40.0 network ID
11111111.11111111.11111111.00000000 - Old subnet mask (/24)
11000000.10101000.00101000.00000000 - 192.168.40.0 network ID
11111111.11111111.11111111.10000000 - New subnet mask (/25)
11000000.10101000.00101000.10000000 - 192.168.40.128 network ID
11111111.11111111.11111111.10000000 - New subnet mask (/25)
Look over that until it makes sense. We increased the subnet mask by one bit in length, causing the network ID to cover one bit that would have been used for host ID. Since that one bit can be either zero or one, we've effectively split our 192.168.40.0 network into two networks. The first valid IP address in the 192.168.40.0/25 network will be the first host ID with a "1" in the right-most bit:
11000000.10101000.00101000.00000001 - 192.168.40.1 - First valid host in the 192.168.40.0/25 network
The first valid host in the 192.168.40.128 network will, likewise, be the first host ID with a "1' in the right-most bit:
11000000.10101000.00101000.10000001 - 192.168.40.129 - First valid host in the 192.168.40.128/25 network
The last valid host in each network will be the host ID with every bit except the right-most bit set to "1":
11000000.10101000.00101000.01111110 - 192.168.40.126 - Last valid host in the 192.168.40.0/25 network
11000000.10101000.00101000.11111110 - 192.168.40.254 - Last valid host in the 192.168.40.128/25 network
So, in this way, we've created a network large enough to hold our client computers, and a second network that we can then apply the same principle to break down into yet smaller networks. Let's make a note:
Client computers - 192.168.40.0/25 - Valid IPs: 192.168.40.1 - 192.168.40.126
Now, to break down the second network for our servers and switches, we do the same thing.
We have 12 server computers, but we might buy up to 6 more. Let's plan on 18, which leaves us the next highest power of 2 as 32. In binary, 32 is "100000", which is 6 bits long. We have 7 bits of subnet mask left in 192.168.40.128/25, so we have enough bits to continue "playing". Adding one more bit of subnet mask gives us two more networks:
11000000.10101000.00101000.10000000 - 192.168.40.128 network ID
11111111.11111111.11111111.10000000 - Old subnet mask (/25)
11000000.10101000.00101000.10000000 - 192.168.40.128 network ID
11111111.11111111.11111111.11000000 - New subnet mask (/26)
11000000.10101000.00101000.10000001 - 192.168.40.129 - First valid host in the 192.168.40.128/26 network
11000000.10101000.00101000.10111110 - 192.168.40.190 - Last valid host in the 192.168.40.128/26 network
11000000.10101000.00101000.11000000 - 192.168.40.192 network ID
11111111.11111111.11111111.11000000 - New subnet mask (/26)
11000000.10101000.00101000.11000001 - 192.168.40.193 - First valid host in the 192.168.40.192/26 network
11000000.10101000.00101000.11111110 - 192.168.40.254 - Last valid host in the 192.168.40.192/26 network
So, now we've broken up 192.168.40.128/25 into two more networks, each of which has 26 bits of subnet mask, or a total of 62 possible host IDs-- 2 ^ (32 - 26) - 2.
That means that both of those networks have enough addresses for our servers and switches! Let's make notes:
Servers - 192.168.40.128/26 - Valid IPs: 192.168.40.129 - 192.168.40.190
Switches - 192.168.40.192/26 - Valid IPs: 192.168.40.193 - 192.168.40.254
This technique is called variable-length subnet masking (VLSM) and, if properly applied, causes "core routers" to have smaller routing tables (through a process called "route summarization"). In the case of our ISP in this example, they can be totally unaware of how we've subnetted 192.168.40.0/24. If their router has a packet bound for 192.168.40.206 (one of our switches), they need only know to pass it to our router (since 192.168.40.206 matches the network id and subnet mask 192.168.40.0/24 in their router's routing table) and our router will get it to the destination. This keeps our subnet routes out of their routing tables. (I'm simplifying here, but you get the idea.)
You can plan very geographically large networks in this same way. As long as you do the right "urban planning" up front (anticipating the number of hosts in each sub-network with some accuracy and an eye to the future) you can create a large routing hierarchy that, at the core routers, "summarizes" to a very small number of routes. As we saw above, the more routes that are in a router's routing table the slower it performs its job. Designing an IP network with VLSM and keeping routing tables small is a Good Thing(tm).
The Unrealism of Examples
The fictional world in this answer is, obviously, fictional. Typically you can make subnets on modern switched Ethernet with more hosts than 254 (traffic profile dependent). As has been pointed out in comments, using /24 networks between routers isn't consistent with Real Life(tm). It makes for cute examples, but is a waste of address space. Typically, a /30 or a /31 (see http://www.faqs.org/rfcs/rfc3021.html for details on how /31's work-- they are beyond the scope of this answer for sure) network is used on links that are strictly point-to-point between two routers.
A:
Sub-netting
Sub-netting is not difficult but it can be intimidating. So let's start with the simplest possible step. Learning to count in binary.
Binary
Binary is a base 2 counting system. Consisting of only two numbers (1 and 0). Counting proceeds in this manner.
1 = 001 ( 0 + 0 + 1 = 1)
2 = 010 ( 0 + 2 + 0 = 2)
3 = 011 ( 0 + 2 + 1 = 3)
4 = 100 ( 4 + 0 + 0 = 4)
5 = 101 ( 4 + 0 + 1 = 5)
So if you just imagine that each 1 is a place holder for a value (all binary values are powers of two)
1 1 1 1 1 = 31
16 + 8 + 4 + 2 + 1 = 31
So... 100000 = 32. And 10000000 = 128. AND 11111111 = 255.
When I say, "I have a subnet mask of 255.255.255.0", I really mean, "I have a subnet mask of 11111111.11111111.11111111.00000000." We use subnets as a short hand.
The periods in the address, separate every 8 binary digits (an octet). This is why IPv4 is known as a 32bit (8*4) address space.
Why Subnet?
IPv4 addresses (192.168.1.1) are in short supply. Sub-netting gives us a way to increase the amount of available networks (or hosts). This is for administrative reasons and technical reasons.
Each IP address is broken into two separate portions, the network and the host. By default a Class C address (192.168.1.1) uses the first 3 octets (192.168.1) for the network portion of the address. and the 4th octet (.1) as the host portion.
By default an ip address and subnet mask for a Class C adress looks like this
IP 192.168.1.1
Subnet 255.255.255.0
In binary like this
IP 11000000.10101000.00000001.00000001
Subnet 11111111.11111111.11111111.00000000
Look at the binary example again. Notice how I said the first three octets are used for the network? Notice how the network portion is all ones? That's all sub-netting is. Let's expand.
Given that I have a single octet for my host portion (in the above example). I can ONLY ever have 256 hosts (256 is the max value of an octet, counting from 0). But there's another small trick: you need to subtract 2 host addresses from the available ones (currently 256). The first address in the range will be for the network (192.168.1.0) and the last address in the range will be the broadcast (192.168.1.255). So you really have 254 available addresses for hosts in one network.
A Case Study
Let's say I gave you the the following piece of paper.
Create 4 networks with 192.168.1.0/24.
Let's take a look at this. The /24 is called CIDR notation. Rather than referencing the 255.255.255.0 we just reference the bits we need for the network. In this case we need 24bits (3*8) from a 32bit address. Writing this out in binary
11111111.11111111.11111111.00000000 = 255.255.255.0
8bits + 8bits + 8bits + 0bits = 24bits
Next we know we need figure out how many subnets we need. Looks like 4. Since we need to create more networks (currently we only have one) lets flip some bits
11111111.11111111.11111111.00000000 = 255.255.255.0 = 1 Network OR /24
11111111.11111111.11111111.10000000 = 255.255.255.128 = 2 Networks OR /25
11111111.11111111.11111111.11000000 = 255.255.255.192 = 4 Networks (remember powers of 2!) OR /26
Now that we've decided on a /26 let's start allocating hosts. A little simple math:
32(bits) - 26(bits) = 6(bits) for host addresses.
We have 6bits to allocate in each network for hosts. Remembering that we need to subtract 2 for each network.
h = host bits
2^h - 2 = hosts available
2^6 - 2 = 62 hosts
Finally we have 62 hosts in 4 networks, 192.168.1.0/26
Now we need to figure out where the hosts go. Back to the binary!
11111111.11111111.11111111.00,000000 [the comma is the new network/hosts division]
Begin to calculate:
11000000.10101000.00000001.00,000000 = 192.168.1.0 [First IP = Network Adress]
11000000.10101000.00000001.00,000001 = 192.168.1.1 [First Host IP]
11000000.10101000.00000001.00,000010 = 192.168.1.2 [Second Host IP]
11000000.10101000.00000001.00,000011 = 192.168.1.3 [Third Host IP]
And so on ... until ...
11000000.10101000.00000001.00,111110 = 192.168.1.62 [Sixty Second Host IP]
11000000.10101000.00000001.00,111111 = 192.168.1.63 [Last IP = Broadcast Address]
So ... On to the NEXT network ....
11000000.10101000.00000001.01,000000 = 192.168.1.64 [First IP = Network Address]
11000000.10101000.00000001.01,000001 = 192.168.1.65 [First Host IP]
11000000.10101000.00000001.01,000010 = 192.168.1.66 [Second Host IP]
And so on ... until ...
11000000.10101000.00000001.01,111110 = 192.168.1.126 [Sixty Second Host IP]
11000000.10101000.00000001.01,111111 = 192.168.1.127 [Last IP = Broadcast Address]
So ... On to the NEXT network ....
11000000.10101000.00000001.10,000000 = 192.168.1.128 [First IP = Network Address]
11000000.10101000.00000001.10,000001 = 192.168.1.129 [First Host IP]
Etc ...
In this way you can calculate the entire subnet.
Wild Cards
A wild card mask is an inverted subnet mask.
11111111.11111111.11111111.11000000 = 255.255.255.192 [Subnet]
00000000.00000000.00000000.00111111 = 0.0.0.63 [Wild Card]
Further
Google for the terms 'super-netting', and 'VLSM (variable length subnet mask)', for more advanced topics.
I can see now that I took too long in responding ... sigh
| {
"pile_set_name": "StackExchange"
} |
Q:
Как изменить размер ImageVew при нажатии? При помощи XML разметки
Есть ImageView :
<ImageView
android:layout_width="76dp"
android:layout_height="76dp"
android:layout_marginTop="42dp"
android:clickable="true"
android:src="@drawable/camera_change_selector"/>
Есть selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_camera_down" android:state_pressed="true"></item>
<item android:drawable="@drawable/btn_camera_up"></item>
</selector>
Как сделать, чтобы при нажатии @drawable/btn_camera_up уменьшалось в размерах при помощи XML?
A:
Вместо изображения для меньшего состояния используешь для селектора следующий ресурс -
camera_up.xml: (Здесь изображение будет уменьшено на 3dp с каждой стороны)
<?xml version="1.0" encoding="utf-8"?>
<inset
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/btn_camera_up"
android:insetTop="3dp"
android:insetRight="3dp"
android:insetBottom="3dp"
android:insetLeft="3dp" />
селектор camera_change_selector.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_camera_down" android:state_pressed="true"></item>
<item android:drawable="@drawable/camera_up"></item>
</selector>
ImageView обязательно должен быть устанавлен атрибут android:clickable = "true"
<ImageView
android:layout_width="76dp"
android:layout_height="76dp"
android:layout_marginTop="42dp"
android:clickable="true"
android:src="@drawable/camera_change_selector"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
does "are you still riding that old car" sound ok?
If I want to joke about my friend's old car, is the sentence correct?
are you still riding that old car?
A:
Are you still riding that old car?
If you travel as a passenger in a car, you can say that you ride a car (in AmE) or ride in a car (both in AmE and BrE). So there's nothing wrong with the sentence if used in this sense.
If you operate a car and control its movement and direction, you say that you drive a car. If used in this sense, the correct sentence is:
Are you still driving that old car?
| {
"pile_set_name": "StackExchange"
} |
Q:
Will Down's syndrome be ever reversible?
Down syndrome is caused by genetic disorder when in DNA chromosome #21 has three copies (instead of 2 copies). If I understand correctly then the Genetic Engineering is the closest field in modern medicine that studies how to alter host's DNA.
Would there in next few years be a cure for Down's syndrome (i.e. remove the third copy of chromosome #21 in an adult's DNA)? If not, then what are difficulties that would still need to be overcome in genetic engineering to do something like that?
For example, is it impossible to consistently change DNA for all cells in body? Would these cells start to "attack" each other while being in partially reconfigured state?). If I understand correctly then CRISPR* method is the new tool in genetic engineering that may allow to do such DNA manipulations?
P.S. as it may be obvious from my question I don't have medical background and my questions is motivated by having relative affected by Down's syndrome.
P.P.S. I found this link http://www.prnewswire.com/news-releases/new-down-syndrome-therapy-discovered-300135102.html - not sure how to interpret it.
A:
Reversing Down Syndrome in adults is not something being currently researched to my knowledge. Alerting the DNA throughout the body of a person at this point is purely science fiction, but even if it were possible the critical structures that were created due to the genetic mutation wouldn't just go away.
Take the simian crease in the hand of many with down syndrome. If you altered the DNA of the entire person they'd still have the simian crease because it was established early in the early formation of the person as an embryo. The genes for creating a hand aren't re-expressed later.
More importantly, many of the brain structures and pathways are formed in early childhood and puberty and a genetic change after then would have little effect.
Genetic alteration research would first be focused on embryonic intervention, but in not aware of any studies actively looking at that even. Most research is focused on early detection, causes/prevention, and therapeutic intervention for mitigation of symptoms. You can see none of the studies currently being conducted by the National Down Syndrome Society or the International Mosaic Down Syndrome Society are related to genetic intervention. These may also give you a feel for the type of research (here, here, and here).
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to send a message from a Content Script to a Background Page using chrome.tabs.sendmessage?
I have found plenty of examples and documentation on sending a message from a background page to a content script, but am unable to find a way to send a message from a content script to a background page.
The reason for this is that I want to use chrome.downloader.download, e.g.
chrome.downloads.download({
"url": randomImageForSpotCheck
}, function () {...
spotcheck(randomImage);
});
A:
First google search brings up:
Sending a request from a content script looks like this:
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
(here)
Into your background script you should have a bit of code listening for such a message:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (sender.tab) {
// is from content script
// access stuff like:
// request.horseradish
sendResponse({});
}
});
and your content script can send the message:
// vv put whatever data you want here
chrome.runtime.sendMessage({horseradish: true}, function(response) {
// this is a callback function to execute,
// response is the object sent by your sendResponse({});
// this one ^^
});
| {
"pile_set_name": "StackExchange"
} |
Q:
ITable.DeleteAllOnSubmit() is absent?
As far as I see ITable<T> interface doesn't have DeleteAllOnSubmit() method that exists in ITable interface and in Table<T> class.
I am going to implement on my own something like this:
public static void DeleteAllOnSubmit<T>(this ITable<T> table, IEnumerable<T> entities)
{
entities.ForEach(entity=>table.DeleteOnSubmit(entity);
}
Question 1: Is there any pitfalls here? If it was so easy Microsoft would implement that thierselves...
Question 2: Why that was not implmemented out-of-the box?
A:
Having a look at the implementation of Table<TEntity>.DeleteAllOnSubmit<TSubEntity>() shows, that there isn't much more going on:
public void DeleteAllOnSubmit<TSubEntity>(IEnumerable<TSubEntity> entities) where TSubEntity: TEntity
{
if (entities == null)
{
throw Error.ArgumentNull("entities");
}
this.CheckReadOnly();
this.context.CheckNotInSubmitChanges();
this.context.VerifyTrackingEnabled();
foreach (TEntity local in entities.ToList<TSubEntity>())
{
this.DeleteOnSubmit(local);
}
}
So, I'd say: Your implementation is just fine.
BTW: There is no ForEach extension method for IEnumerable<T>.
| {
"pile_set_name": "StackExchange"
} |
Q:
Arithmetic operation resulted in an overflow—blowfish algorithm
When I execute this code:
Dim bytearray() As Byte = System.IO.File.ReadAllBytes("C:\Users\Fery Ferdiansyah\Desktop\asd\asd.txt")
Dim key() As Byte = System.Text.Encoding.UTF8.GetBytes("swagger")
Dim bf As New blowfish2(key)
this syntax y = S(0, a) + S(1, b) in this function causes arithmetic overflow:
Private Function F(ByVal x As UInteger) As UInteger
Dim a As UShort
Dim b As UShort
Dim c As UShort
Dim d As UShort
Dim y As UInteger
d = CUShort((x And &HFF))
x >>= 8
c = CUShort((x And &HFF))
x >>= 8
b = CUShort((x And &HFF))
x >>= 8
a = CUShort((x And &HFF))
y = S(0, a) + S(1, b)
y = y Xor S(2, c)
y = y + S(3, d)
Return y
End Function
Could anyone help me to fix this function?
A:
The result of adding two integers (Int32) has to be stored into a Int64 to be sure that the result can be stored without overflow.
So in this case your method should return a UInt64 and y should be UInt64 as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
ERROR Error: No provider for JwtHelper
I'm new to Angular2 and i'm using jwthelper to encode the jwt token and extract the details.
import { Injectable } from '@angular/core';
import { JwtHelper } from 'angular2-jwt';
@Injectable()
export class SessionService {
constructor(private jwtHelper: JwtHelper){}
getUser(){
var token = JSON.parse(localStorage.getItem('currentUser'));
return this.jwtHelper.decodeToken(token.token);
}
}
Couldn't find a solution for the following error and show me what is incorrect here.
ERROR Error: No provider for JwtHelper!
A:
This is because you are trying to inject JwtHelper in the constructor of your component/service. This is done only for providers.
According to using jwthelper in components section, you have to create a new object and use it.
In your service,
constructor(){} //remove from constructor.
getUser(){
let jwtHelper: JwtHelper = new JwtHelper();
var token = JSON.parse(localStorage.getItem('currentUser'));
return this.jwtHelper.decodeToken(token.token);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Handling the double-click event of a user control with many children controls
I have a user control consisting of many children controls, and I need to handle the user control's double-click event. So I add the event handler but it's never triggered.
The quickest solution I am finding is to iterate through the children controls and subscribe to their double-click events. Is this really the right way to do it? Are there better ways? Thank you.
A:
The following will work only for the first level children control which are being added to the user control. It will not work for the controls which are added subsequently to these children. For example, it will work for a double-click on a first level Panel child control, but not on a Label which is added to the panel.
Test.cs
public partial class Test : UserControl
{
public Test()
{
InitializeComponent();
}
protected override void OnControlAdded(ControlEventArgs e)
{
e.Control.DoubleClick += Control_DoubleClick;
base.OnControlAdded(e);
}
void Control_DoubleClick(object sender, EventArgs e)
{
MessageBox.Show("User control clicked");
OnDoubleClick(e);
}
}
Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var test = new Test();
var label = new Label();
label.Text = "test";
test.Controls.Add(label);
Controls.Add(test);
}
}
To address the other case, when you have controls contained inside controls, you can use the following code. Be sure to add the user control to it's parent control before adding any other child controls to it. Once you do that, follow the same principle as you go down the control hierarchy.
To put it simpler, before adding a control anywhere in the control hierarchy, make sure that it's parent is already added to a control collection.
Test.cs
protected override void OnControlAdded(ControlEventArgs e)
{
e.Control.DoubleClick += Control_DoubleClick;
e.Control.ControlAdded += OnControlAdded; // add this line
base.OnControlAdded(e);
}
// add this method
private void OnControlAdded(object sender, ControlEventArgs e)
{
e.Control.DoubleClick += Control_DoubleClick;
e.Control.ControlAdded += OnControlAdded;
}
Form1.cs
private void Form1_Load(object sender, EventArgs e)
{
var test = new Test();
var panel1 = new Panel();
panel1.BackColor = Color.AliceBlue;
var panel2 = new Panel();
panel2.BackColor = Color.AntiqueWhite;
var label1 = new Label();
label1.Text = "test 1";
label1.BackColor = Color.Aquamarine;
var label2 = new Label();
label2.Text = "test 2";
label2.BackColor = Color.Azure;
// !!! order is important !!!
// first add at least one child control to the test control
// this works as expected
//Controls.Add(test);
//test.Controls.Add(panel1);
//panel1.Controls.Add(panel2);
//panel2.Left = 50;
//panel1.Controls.Add(label1);
//panel2.Controls.Add(label2);
// this works as expected
//test.Controls.Add(panel1);
//Controls.Add(test);
//panel1.Controls.Add(panel2);
//panel2.Left = 50;
//panel1.Controls.Add(label1);
//panel2.Controls.Add(label2);
// this doesn't work for panel2 and it's children
Controls.Add(test);
panel1.Controls.Add(panel2); // panel2 & children will not trigger the events
// all controls added to control collections
// prior to this line will not trigger the event
test.Controls.Add(panel1);
panel2.Left = 50;
panel1.Controls.Add(label1);
panel2.Controls.Add(label2); // will not trigger the event
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Ninject WCF: Attribute Injection
I am using the Ninject WCF extension project to do dependency injection on my web service. If I add an attribute to my web service (such as a an IServiceBehavior), how can I inject dependencies into that attribute when it is created at runtime?
A:
Attributes are created by the .NET Runtime. Therefore there is no real dependency injection for them. You should try to avoid having attributes that require dependencies whenever possible. You have the following options:
Service behaviors can be added without attributes. But this requires that you extend the current WCF Extension with some way to define that you want to add a service behavior for some instances in a similar way as it is currently possible for MVC Filters. This is done here: https://github.com/ninject/ninject.extensions.wcf/blob/master/src/Ninject.Extensions.Wcf/ServiceHost/NinjectServiceHost.cs
You can implement an IInstance provider which searches your attributes and injects them. See https://github.com/ninject/ninject.extensions.wcf/blob/master/src/Ninject.Extensions.Wcf/NinjectInstanceProvider.cs
I'd try to go with the first option.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why IDs start with com.?
Like this one:
<widget xmlns = "http://www.w3.org/ns/widgets"
xmlns:gap = "http://phonegap.com/ns/1.0"
id = "com.phonegap.helloworld"
version = "1.0.0">
I see it also in Java and Android.
What does com mean? What is phonegap here? The company or the web site of the company?
A:
There's no technical reason why IDs or package names must start with com. However, no two apps can have the same package name, so the convention is to name your app based on your website's url in reverse. That convention means that no two apps will conflict, at least as long as ownership of your domaian doesn't change. In this case, this is made by phonegap.com, so their package name is com.phonegap.xxx, where x is a name they pick.
Phonegap is a cross-platform app development tool, so that you can write one set of code for both Android and iOS.
| {
"pile_set_name": "StackExchange"
} |
Q:
How come the close button link doesn't work for the telerik:RadNotification control on DotNetNuke?
I'm using the telerik:RadNotification control, with VisibleTitlebar="true" ShowTitleMenu="false" and ShowCloseButton="true".
When I hover over the little X (close button) the URL is "http://localhost/mySite/href". When I click on it it takes me to an HTTP Error 404.0 - Not Found page.
Any advice would be greatly appreciated. Is there any way to programmaticly fix the bad link?
I tried adding an OnClientHiding="OnClientHiding" and adding an javascript alert in the OnClientHiding method but it goes to the error page first.
A:
My problem was that I was not getting into the OnClientHiding event handler. It looks like some code in the OnClientShown event handler was causing this issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Weird python bug. Variable changes value without any modification
In the function "enText" changes its value even though I don't modify it.
e = 5 and n = 6. enText is an array of ints.
I modify the values in the array after passing it to changeTxt. I then return changeTxt but for some reason enText ends up being modified as well.
No idea why.
#Function for encryption
def encrypt(e, n, enText):
#e=5 & n=6
changeTxt = enText
print(enText)
#prints [18, 15, 2, 9, 14]
for x in range(0, len(changeTxt)):
#problem here!!!!!!!!
tmp = changeTxt[x]**e
tmp = tmp % n
changeTxt[x] = tmp
print(enText)
#prints [0, 3, 2, 3, 2]
return changeTxt
A:
Your line
changeTxt = enText
only copies the reference to the list, but both point to the same list. So changes to changeTxt will affect enText as well.
Instead try to clone the list like this:
changeTxt = enText[:]
or
changeTxt = list(enText)
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular 8 Display preview of two image input
I have two input of uploading image and I want to display a preview of those two, for one input it works correctly !
<div class="col-md-2 mb-3">
<label for="">Icon</label>
<input style="display: none" type="file" (change)="onIconChanged($event)" #fileInput>
<div class="card-img-top"
[style.background]="displayIcon ? 'url(' + displayIcon + ')' : 'url(http://via.placeholder.com/100x100)'"
style="width: 100px;height: 100px;"></div>
<button type="button" class="buupload" (click)="fileInput.click()">Upload</button>
</div>
<div class="col-md-8 mb-3">
<label for="">Banner</label>
<input style="display: none" type="file" (change)="onBannerChanged($event)" #fileInput>
<div class="card-img-top"
[style.background]="displayBanner ? 'url(' + displayBanner + ')' : 'url(http://via.placeholder.com/550x100)'"
style="width: 550px;height: 100px;"></div>
<button type="button" class="buupload" (click)="fileInput.click()">Upload</button>
</div>
** ts **
onIconChanged(event) {
this.selectedIcon = event.target.files[0]
if (event.target.files && event.target.files[0]) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = e => this.displayIcon = reader.result;
reader.readAsDataURL(file);
}
}
onBannerChanged(event) {
this.selectedBanner = event.target.files[1]
if (event.target.files && event.target.files[1]) {
const file = event.target.files[1];
const reader = new FileReader();
reader.onload = e => this.displayBanner = reader.result;
reader.readAsDataURL(file);
}
}
the display of banner input not working and it always appears on the first input preview (icon) !!
A:
Please change the second input referance and try again.
<div class="col-md-8 mb-3">
<label for="">Banner</label>
<input style="display: none" type="file" (change)="onBannerChanged($event)" #secondFileInput>
<div class="card-img-top"
[style.background]="displayBanner ? 'url(' + displayBanner + ')' : 'url(http://via.placeholder.com/550x100)'"
style="width: 550px;height: 100px;"></div>
<button type="button" class="buupload" (click)="secondFileInput.click()">Upload</button>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Twisted execute python file
Is there any way to get a twisted webserver to execute a python file like cgi on a conventional webserver? So, when i navigated to a directory, i could execute python within a seperate file?
I have created a basic webserver, but it only returns static content like text or HTML files:
from twisted.web.server import Site
from twisted.web.static import File
from twisted.internet import reactor
resource = File('/root')
factory = Site(resource)
reactor.listenTCP(80, factory)
reactor.run()
I understand why it may not be possible, but i couldn't find any documentation. Thanks
EDIT: I found a solution. Instead of going through the hassle of directories, i'm simply parsing GET requests and treating them like fake files. The CGI is executed within the main file.
THanks
A:
Found this example that might do what you want.
Take a look Twisted Web Docs for some more info. Search the page for CGI.
from twisted.internet import reactor
from twisted.web import static, server, twcgi
root = static.File("/root")
root.putChild("cgi-bin", twcgi.CGIDirectory("/var/www/cgi-bin"))
reactor.listenTCP(80, server.Site(root))
reactor.run()
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.