text:
Q: How to connect MS SQL Server Express Edition with Splunk DB Connect v1? I am trying to connect Microsoft SQL Server 2012 Express Edition with Splunk DB Connect V1 through GUI with Following information:
Name- RSD(name given to identify uniquely in splunk)

Database Type - Microsoft SQL Server

Host - IP Address of my own System Since Database is running locally

Port - 1433

Username - sa

Password - Password which is used for SQL Server Authentication

Additional JDBC Parameters - useCursors=true

When I click on Fetch database names. It gives an ERROR java.sql.SQLException: Network error IOException: Connection refused: connect.
Or, I entered database name manually:
Database - name of my database and click on save then, it gives same error as above.
I have found following logs in dbx.log file
enter code here
2015-04-29 09:34:33.164 dbx7826:INFO:BridgeSession - Executing Bridge command: BridgeExecutionInfo{className=com.splunk.dbx.info.DatabaseList}
2015-04-29 09:34:35.223 dbx7826:ERROR:DatabaseList - Error fetching database catalogs: java.sql.SQLException: Network error IOException: Connection refused: connect
java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:436)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.splunk.dbx.sql.type.impl.AbstractDatabaseType.connect(AbstractDatabaseType.java:139)
at com.splunk.dbx.sql.type.impl.MicrosoftSqlServer.connect(MicrosoftSqlServer.java:85)
at com.splunk.dbx.sql.type.impl.AbstractJtdsDatabaseType.listCatalogs(AbstractJtdsDatabaseType.java:48)
at com.splunk.dbx.info.DatabaseList.invoke(DatabaseList.java:34)

I have looked through any related answers that I could find, but no luck.
Some help and insight would be appreciated.

A: I have tried with windows authentication DOMAIN/password.THE error is resolved windows firewall is blocking the port 1433.just make sure that browser services are running and sql services are running ,allow port 1433.it works


text:
Q: slicing a jpg with vb.net since i do not have any image editing software, i am going to use vb.net to slice an image horizontally. can someone help me get started please?

A: In the code below you first load the image, then create a new image with the new width and height, grab the Graphics object from it and finally draw the old image onto the new image. We draw the old image onto the new image using the old image's dimensions but since the new image is smaller the rest will be off of the canvas.
    Private Shared Sub CropImage(ByVal inputImagePath As String, ByVal outputImagePath As String, ByVal newHeight As Integer)
    Using oldImage = System.Drawing.Image.FromFile(inputImagePath)
        Using NewImage As New System.Drawing.Bitmap(oldImage.Width, newHeight)
            Using G = Graphics.FromImage(NewImage)
                G.DrawImage(oldImage, 0, 0, oldImage.Width, oldImage.Height)
                NewImage.Save(outputImagePath, System.Drawing.Imaging.ImageFormat.Jpeg)
            End Using
        End Using
    End Using
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Twitter4J: How to solve the rate limit request of Twitter API? I am creating a java application that interact with Twitter using the library Twitter4J.
I want to download 10 000 nodes from twitter, and then do the statistics on the graph created. The graph is initially saved in a dataset (.txt file).
I must also save enough ReTweet for each node (so I have to check their timeline).
Skipping the instantiation of twitter to perform queries, I have two problems and doubts:
1) How do I manage the problem that the Twitter API have a limited number of required into a slot 15 minutes?
I tried this:
public static RateLimitStatus getApplicationRateLimitStatus(Twitter twitter)
{
    try {
        Map<String ,RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus();
        for (String endpoint : rateLimitStatus.keySet())
        {
            if (endpoint.equals("/application/rate_limit_status"))
                return rateLimitStatus.get(endpoint);
        }
    } catch (TwitterException te)
        {
            te.printStackTrace();
            System.out.println("Failed to get rate limit status: " + te.getMessage());
            System.exit(-1);
        }
    return null;
}

public static void control(Twitter twitter)
{
    RateLimitStatus app_rate_limit_st = null;
    RateLimitStatus user_timeline_limit_st = null;
    RateLimitStatus credentials_limit_st = null;
    RateLimitStatus friends_list_limit_st = null;
    RateLimitStatus followers_list_limit_st = null;
    int ctr_req = 7;

    try {
        if ((app_rate_limit_st = MyRateLimit.getApplicationRateLimitStatus(twitter)).getRemaining() < ctr_req)
        {
            System.out.println("I'm waiting "+app_rate_limit_st.getSecondsUntilReset()+" seconds for Application Rate Limit, app request remaining: "+app_rate_limit_st.getRemaining());
            Thread.sleep((long)app_rate_limit_st.getSecondsUntilReset()*1000);
            System.out.println("I woke up!!!");
        }
    }catch(InterruptedException e) {e.printStackTrace();}
}

In this block of code I checked only requests ApplicationRequest type, but in my application I checked also required type FriendList, FollowersList, UserTimeline and Credentials.
By running my application, is raised that notification
I have exceeded the number of available applications, and can not understand why.
2)
Another problem is with which algorithm should proceed to download the nodes.
I thought about taking a popular node (has many friends and followers, and who interact much with each other).
I tried to take the node, on the friends, his followers, and then the friends and followers of the friends and the friends and followers of followers.
It's a clever technique? They would know better?
Thanks.

A: Just a thought on how you can workaround the rate limit problem -
Create multiple twitter oauth credentials, you can maintain a list/set of Twitter instance configured with each available  credential, when you reach a rate limit for say id1, you can switch to use id2 to fetch records.
Instead of using getApplicationRateLimitStatus, check for functional rate limit status and make a switch, this would help you plan the switch based on available limit for that API.
--Adding code/comments below as per the review comments,
You can do something like below, for each request you can use a connector, in your case you may need to cache few information that can be used to make next call like sinceId and maxId.
You would need to create/register multiple twitter accounts and generate credentials for each of them. I had tried this approach to fasten up fetching information for about 1 M users and it was effective.
You can also cache some recurring information and save few hits to Twitter, like in a network of 10 people its possible to have some percentage of common users/followers so to lookup user information a previously fetched user can be skipped in next request.
getTweetConnector() method will ensure you get a connector that has reset its ratelimit.
Since you are fetching information through multiple API's you can batch up connectors for specific request such that API's with higher rateLimit can have more connectors.
public class TweetUserInfo {
private Set<Twitter> mTwitterConnectorsSet;
private BufferedReader mUserFileReader;

TweetUserInfo(){
    mTwitterConnectorsSet = new HashSet<Twitter>();
}

private void initTweetConnectors(String inFile) {
    BufferedReader br = null;
    try {
        String line = null;
        String[] lines = new String[4];
        int linesIndex = 0;
        br = new BufferedReader(new FileReader(inFile));

        while ((line = br.readLine()) != null) {
            if (linesIndex == 4) {
                createAndAddTwitterConnector(lines);
                linesIndex = 0;
            }
            lines[linesIndex] = line;
            ++linesIndex;
        }
        if (linesIndex == 4) {
            createAndAddTwitterConnector(lines);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

private void createAndAddTwitterConnector(String[] lines) {
    ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
    twitterConfigBuilder.setDebugEnabled(true);

    for (int i = 0; i < lines.length; ++i) {
        String[] input = lines[i].split("=");

        if (input[0].equalsIgnoreCase("consumerkey")) {
            twitterConfigBuilder.setOAuthConsumerKey(input[1]);
        }
        if (input[0].equalsIgnoreCase("consumersecret")) {
            twitterConfigBuilder.setOAuthConsumerSecret(input[1]);
        }
        if (input[0].equalsIgnoreCase("accesstoken")) {
            twitterConfigBuilder.setOAuthAccessToken(input[1]);
        }
        if (input[0].equalsIgnoreCase("accesstokensecret")) {
            twitterConfigBuilder.setOAuthAccessTokenSecret(input[1]);
        }
    }
    Twitter twitter = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
    mTwitterConnectorsSet.add(twitter);
}

private Twitter getTweetConnector() {
        for (Twitter tc : mTwitterConnectorsSet) {
            try {
                if (tc.getRateLimitStatus() != null) {
                    if (tc.getRateLimitStatus().containsKey("/users/lookup")) {
                        if (tc.getRateLimitStatus().get("/users/lookup") != null) {
                            System.out.println("tc - "+tc);
                            System.out.println("tc rate - "+tc.getRateLimitStatus().get("/users/lookup").getRemaining());
                            if (tc.getRateLimitStatus().get("/users/lookup").getRemaining() > 2) {
                                return tc;
                            }
                        }
                    }
                }
            } catch (TwitterException e) {
                e.printStackTrace();
            }
        }
    return null;
}

}
Hope this helps.


text:
Q: dynamically change radio button height and font size in jquery mobile I'm trying to change height and font size of horizontal controlgroup radio buttons dynamically with jquery mobile 1.2.1
I can change size and font, but with some values the buttons are displayed toghether with the basic radio selector as in
http://picpaste.com/Capture-94sE5bZi.PNG
http://jsfiddle.net/mauix/VVpR9/15/

<form>
<fieldset data-role="controlgroup" data-type="horizontal" id="btnc1">
    <input name="rc" id="rca" value="on" checked="checked" type="radio">
    #1
    <input name="rc" id="rcb" value="off" type="radio">
    #2
    <input name="rc" id="rcc" value="other" type="radio">
    #3
</fieldset>
</form>

thanks for help

A: jQM enhances the radio button by replacing its markup, however, it leaves the original input tag in the dom under the new markup vertically centered within the radio div.  When you set the height to 100px, the enhanced button stays at the top while the input moves to the middle and becomes visible.  Here are 2 options:
Don't resize the button, just change the font size and let the buttons auto-size with the font changes:

DEMO

If you need the button size changed to exact height, you can use CSS to hide the input:
.ui-radio input{
    display: none;
}

DEMO


text:
Q: JS and text encoding I have a text file with accented characters like é. I used File Encoding Checker, it appears that the file is encoded as windows-1252.
I read the file with the following JS and node.js code:
fs.readFile('frenchVerbsList.txt','utf-8', function(err, data) {
    if (err) {
        return console.log("ERROR here!: " + err);
    }
    frenchWords = data.split('\r\n');
    console.log(frenchWords);
});

The output from the console.log statement shows a question mark instead of the accented characters.
What has happened?

A: Node only supports some encodings and windows-1252 is not part of it. You need to convert the encoding with, for example, encoding to, for example, utf-8.
Similar to this, but haven't tested
var encoding = require("encoding");

fs.readFile('frenchVerbsList.txt', function(err, text) {
    if (err) return console.log("ERROR here!: " + err);

    var resultBuffer = encoding.convert(text, 'utf8', 'windows1252');
    frenchWords = resultBuffer.toString().split('\r\n');

    console.log(frenchWords);
})


text:
Q: Accessing custom attribute array in d3js tree node I am pretty new to the D3JS library but is it possible to add a custom attribute to the json file for the tree layout to process and retrieve the data while building the tree if the particular attribute is not empty?
For example:
{
      "name": "Josphen",
      "id": "1",
      "children": [
        {
         "name": "Ronald",
         "id": "3"
        },
        {
         "name": "Coxy",
         "id": "4",
         "spouse": [
          {
           "name": "baby",
           "id": "5"
          }
         ]
       }
     ]
    }
Would later allow me to retrieve attribute with id=5 while generating the node of id=4.
Any insight into this is appreciated.


text:
Q: Why can't I create an ad-hoc wireless network using Intel 4965AGN? I'm running Ubuntu 11.10 and I want to create a ad-hoc wireless network. I get that my wireless card (INTEL 4965AGN) apparently does not support the ad-hoc mode:
$ sudo service network-manager stop
network-manager stop/waiting
$ sudo ip link set wlan0 down
$ sudo iwconfig wlan0 mode ad-hoc
Error for wireless request "Set Mode" (8B06) :
SET failed on device wlan0 ; Operation not supported.

On Windows instead an ad-hoc network works just fine. I checked here but it seems like all available drivers should be embedded already.
Does anybody have a similar issue? maybe with another card and there's some way to activate the functionality.
Alternatively, could you please suggest some usb wifi adapter that supports ad-hoc?

A: If you are on 11.10, edit the network and set ipv6 to be ignored:


text:
Q: Cannot invoke "com.ros.hr.mapper.EmployeeMapper.convertToDto(com.ros.hr.model.employee)" because "this.mapper" is null when am trying to hit the get all employee url in post man getting error showing and anfter compiling this it's not creating any file in target folder.
error console:
enter image description here
package com.ros.hr.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeDto {

    private long empId;
    private String firstName;
    private String lastName;
    private String profilePic;
    private String email;
}

package com.ros.hr.EmployeeController;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ros.hr.dto.EmployeeDto;
import com.ros.hr.model.employee;
import com.ros.hr.service.EmployeeService;

@RestController
@CrossOrigin("*")
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService empService;

    @PostMapping("/add")
    @ResponseBody
    public employee create(@RequestBody employee e) throws Exception {

        employee response = empService.addEmployee(e);
        if (response == null) {
            throw new Exception("Employee Already Exist Exception");
        }
        return response;
    }

    @GetMapping("/viewAllEmployee")
    public List<EmployeeDto> get() throws Exception {

        List<EmployeeDto> response = empService.viewAllEmployees();
        if (response == null)
            throw new Exception("No Employee's Found");
        return response;
    }

    @GetMapping("/viewEmployee/{Id}")
    public EmployeeDto get(@PathVariable(value = "Id") long Id) throws Exception {

        EmployeeDto response = empService.viewEmployeeById(Id);
        if (response == null)
            throw new Exception("Employee Not Found");

        return response;
    }

    @PutMapping("/editEmployee")
    public EmployeeDto updateEmployee(@RequestBody EmployeeDto empDto) throws Exception {
        EmployeeDto response = empService.editEmployee(empDto);

        if (response == null) {
            throw new Exception("Emnployee DoesNot Exist");
        } else
            return response;
    }

    @DeleteMapping("/deleteEmployee/{id}")
    public String deleteEmployee(@PathVariable(value = "id") long id)throws Exception{
        String response = empService.deleteEmployeeById(id);

        if(response == null) {
            throw new Exception("Employee not found");
        }
        else
            return response;
    }

}

package com.ros.hr.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.factory.Mappers;
import org.springframework.stereotype.Component;

import com.ros.hr.dto.EmployeeDto;
import com.ros.hr.model.employee;

@Mapper(componentModel = "spring")
public interface EmployeeMapper {

    //EmployeeMapper instance = Mappers.getMapper(EmployeeMapper.class);

    //@Mapping(source = "emp.empId",target ="empId")
    EmployeeDto convertToDto(employee emp);

    employee convertToEntity(EmployeeDto empDto);

    /*
    @Mapping(target="dto.empId",source = "empId")
    @Mapping(target="firstName",source = "firstName")
    @Mapping(target="lastName",source = "lastName")
    @Mapping(target="profilePic",source = "profilePic")
    @Mapping(target="email",source = "email")
    employee convertToemployeeEntity(EmployeeDto dto);

    @Mapping(target="entity.empId",source = "empId")
    @Mapping(target="firstName",source = "firstName")
    @Mapping(target="lastName",source = "lastName")
    @Mapping(target="profilePic",source = "profilePic")
    @Mapping(target="email",source = "email")
    @Mapping(target = "middleName",source = "middleName")
    @Mapping(target = "joiningDate",source = "joiningDate")
    @Mapping(target="mobileNum",source="mobileNum")
    @Mapping(target="telePhone",source="telePhone")
    EmployeeDto convertToEmployeeDto(employee entity);
    */
    //@Mapping(target="address",source="address")
        //@Mapping(target="departmentDetails.name",source="departmentDetails.department.name")
        //@Mapping(target="departmentDetailsDto.description",source="departmentDetails.department.description")
        //@Mapping(target="document",source="document")
        //@Mapping(target="employeeBankInfoDto",source="employeeBankInfo")
        //@Mapping(source="employeeBankInfo.salaryInfo.salary",target="employeeBankInfo.salary")
        //@Mapping(target="employeeBankInfoDto.employeeType",source="employeeBankInfo.salaryInfo.employeeType")
        //@Mapping(target="employeeKin.address",source="employeeKin.address")
        //@Mapping(target="statutory",source="statutory")
        //@Mapping(target="statement",source="statement")
//      @Mapping(source = "entity.empId", target = "empId")
//      EmployeeDto convertToEmployeeDto(employee entity);
//

//      @Mapping(source="addressDto",target="address")
//      @Mapping(source="departmentDetailsDto.name",target="departmentDetails.department.name")
//      @Mapping(source="departmentDetailsDto.description",target="departmentDetails.department.description")
//      @Mapping(source="documentDto",target="document")
//      @Mapping(source="employeeBankInfoDto",target="employeeBankInfo")
//      @Mapping(source="employeeKinDto.addressDto",target="employeeKin.address")
//      @Mapping(source="statutoryDto",target="statutory")
//      @Mapping(source="statementDto",target="statement")
//      @Mapping(target ="empId", source = "dtoto.empId")
//      employee convertToEmployeeEntity(EmployeeDto dto);
//
//      void updateEmployee(EmployeeDto employeeDto, @MappingTarget employee emp);
}

package com.ros.hr.model;

import java.util.Date;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "emp_id")
    private long empId;

    private Date joiningDate;
    private String firstName;
    private String middleName;
    private String lastName;
    private String email;
    private long mobileNum;
    private long telePhone;
    private String profilePic;

}

package com.ros.hr.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.ros.hr.model.employee;

@Repository
public interface EmployeeRepository extends JpaRepository<employee, Long>{

}

package com.ros.hr.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.ros.hr.dto.EmployeeDto;
import com.ros.hr.model.employee;

@Service
public interface EmployeeService {

    employee addEmployee(employee emp)throws Exception;

    EmployeeDto viewEmployeeById(long empId);

    List<EmployeeDto> viewAllEmployees();

    String deleteEmployeeById(long id);

    EmployeeDto editEmployee(EmployeeDto employeeDto);

}

package com.ros.hr.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ros.hr.dto.EmployeeDto;
import com.ros.hr.mapper.EmployeeMapper;
import com.ros.hr.model.employee;
import com.ros.hr.repository.EmployeeRepository;
import com.ros.hr.service.EmployeeService;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository empRepo;

    //@Autowired
    private EmployeeMapper mapper;

    @Override
    public employee addEmployee(employee emp) throws Exception {
        // TODO Auto-generated method stub
        if(empRepo.existsById(emp.getEmpId())) {
            return null;
        }
        else
            return empRepo.save(emp);

    }

    @Override
    public EmployeeDto viewEmployeeById(long empId) {
        // TODO Auto-generated method stub
        if(empRepo.existsById(empId)) {
            return mapper.convertToDto(empRepo.findById(empId).get());

        }
        else
            return null;

    }

    @Override
    public List<EmployeeDto> viewAllEmployees() {
        // TODO Auto-generated method stub
        List<EmployeeDto> employeeDto = new ArrayList<EmployeeDto>();
        if(empRepo.count()>0) {
            for(employee em : empRepo.findAll()) {
                employeeDto.add(mapper.convertToDto(em));
                return employeeDto;

            }
        }
            return null;

    }

    public long countEmployee() {
        return empRepo.count();
    }

    @Override
    public String deleteEmployeeById(long id) {
        // TODO Auto-generated method stub
        if(empRepo.existsById(id)) {
            empRepo.deleteById(id);
            return "employee Deleted";
        }else
            return "employee does not exist";

    }

    @Override
    public EmployeeDto editEmployee(EmployeeDto employeeDto) {
        // TODO Auto-generated method stub
        if(empRepo.existsById(employeeDto.getEmpId()))
        {
            employee emp = empRepo.findById(employeeDto.getEmpId()).get();
            emp.setEmpId(employeeDto.getEmpId());
            emp.setEmail(employeeDto.getEmail());
            emp.setFirstName(employeeDto.getFirstName());
            emp.setLastName(employeeDto.getLastName());
            emp.setProfilePic(employeeDto.getProfilePic());

            return mapper.convertToDto(empRepo.saveAndFlush(emp));

        }

        return null;
    }

}

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.3</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ros.hr.employee</groupId>
    <artifactId>AccountingServicEmployee</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>AccountingServicEmployee</name>
    <description>Implementation employee layer</description>
    <properties>
        <java.version>17</java.version>
        <mapstruct.version>1.4.2.Final</mapstruct.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>1.4.2.Final</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>1.4.2.Final</version>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok-mapstruct-binding</artifactId>
                            <version>0.2.0</version>
                        </path>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

server:
  port: 8081

spring:
  application:
    name: hr-service
  datasource:
    url: jdbc:mysql://localhost:3306/employee
    username: root
    password: 1234
  jpa:
    hibernate:
      ddl-auto: update
    properties:
     hibernate:
       database-platform: org.hibernate.dialect.MySQL5InnoDBDialect

i have tried to compile that file but after compiliation not able to build the mapping files in target folder


text:
Q: log shipping of biztalk database on SQL server 2008 standard edition I want to do log shipping for biztalk databases on SQL server 2008 standard edition (server A) to another SQL server 2008 standard edition (server B).
I was told that for biztalk, logshipping is not like standard logshipping.
I was able to find 2 links:
http://msdn.microsoft.com/en-us/library/cc296836%28v=BTS.10%29.aspx
http://msdn.microsoft.com/en-us/library/cc296741%28v=BTS.10%29.aspx
but they are not talking about SQL 2008 servers.
Can anyone please help in this?
Thanks in advance

A: Biztalk does not support any form of sql server log shipping.  Biztalk uses marked transaction log backups to restore on a scheduled basis.  For 2009 see What Is BizTalk Server Log Shipping?


text:
Q: android graphQL apollo I'm using apollo-GraphQL for API response. I have set token in Interceptor class. In main activity I'm using apolloClient, in which I'm passing query to fetch data.
I'mm getting API response from interceptor class but not getting query response.
public class HttpInterceptor implements Interceptor {

    @Override public Response intercept(Interceptor.Chain chain) throws IOException {

        java.util.logging.Logger logger = java.util.logging.Logger.getLogger("okhttp");
        String BASE_URL = "url_example.json";
        Response response = null;
        Request request = chain.request();

        request =chain.request();

        request = request.newBuilder()
                .url(BASE_URL)
                .header("token_key", "token_value")
                .build();

        long t1 = System.nanoTime();

        logger.info(String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));
        response = chain.proceed(request);

        long t2 = System.nanoTime();

        logger.info(String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        return response;
    }

code of Application class:
private static final String BASE_URL = "url_example.json";
private ApolloClient apolloClient;

@Override public void onCreate() {
    super.onCreate();

    OkHttpClient okHttpClient  = new OkHttpClient.Builder()
            .addInterceptor(new HttpInterceptor())
            .build();

    apolloClient = ApolloClient.builder()
            .serverUrl(BASE_URL)
            .okHttpClient(okHttpClient)
            .build();
}

public ApolloClient apolloClient() {
    return apolloClient;
}

code or MainActivity:
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        application = (SampleApplication) getApplication();

        content = (ViewGroup) findViewById(R.id.rl_content_holder);
        progressBar = (ProgressBar) findViewById(R.id.loading_bar);
        RecyclerView collectionRecyclerView = (RecyclerView) findViewById(R.id.rv_collection_list);
        mCollectionAdapter = new CollectionAdapter(this);
        collectionRecyclerView.setAdapter(mCollectionAdapter);
        collectionRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        fetchCollection();
    }

    ApolloCall.Callback<ShopifyCollections.Data> mDataCallback =
            new ApolloCall.Callback<ShopifyCollections.Data>() {
        @Override
        public void onResponse(@Nonnull com.apollographql.apollo.api.Response<ShopifyCollections.Data> response) {
            Log.i("Shopify CallBack",response.toString());
        }

        @Override
        public void onFailure(@Nonnull ApolloException e) {
            Log.e(TAG, e.getMessage(), e);

        }
    };

    public  void fetchCollection(){

        mHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new HttpInterceptor())
                .build();
        ShopifyCollections collectionQuery = ShopifyCollections.builder()
                .limit(250)
                .build();
        collectionCall = application.apolloClient().newCall(collectionQuery);
        collectionCall.enqueue(mDataCallback);
}

Query :
query ShopifyCollections($limit: Int!){
    shop{
        name
        collections(first: $limit)
{
            edges{
                node{
                    title
                    id
                  image{
                    src
                  }
                }
            }
        }
    }
}

A: I see you are trying to write example with Shopify storefront GraphQL schema? If yes then you can find example at: https://github.com/Shopify/mobile-buy-sdk-android/tree/develop-v3/MobileBuy/sample
It's not finished yet but can give you some overview.
If the question is related how to attach auth token to the header:
OkHttpClient httpClient = new OkHttpClient.Builder()
      .addInterceptor(chain -> {
        Request original = chain.request();
        Request.Builder builder = original.newBuilder().method(original.method(), original.body());
        builder.header("User-Agent", "Android Apollo Client");
        builder.header("X-Shopify-Storefront-Access-Token", shopifyApiKey);
        return chain.proceed(builder.build());
      })
      .build();

apolloClient = ApolloClient.builder()
      .okHttpClient(httpClient)
      .serverUrl(HttpUrl.parse("https://" + shopUrl + "/api/graphql"))
      .withCustomTypeAdapter(CustomType.MONEY, new CustomTypeAdapter<BigDecimal>() {
        @Override public BigDecimal decode(final String value) {
          return new BigDecimal(value);
        }

        @Override public String encode(final BigDecimal value) {
          return value.toString();
        }
      })
      .build();


text:
Q: Using classes wrong? so i have very low experience working with classes, but to my project i need to. So i'm doing an app for a bus station, that show the schedule and stuff. So i thought about using classes so its easier to add and remove the timings i want so then after i can send the final to an ArrayList to show on a ListView. But i'm bettin RuntimeExceptions on my class, i don't know if i'm doing it wrong or not, cause i have low experience, i'll show you guys what i have, its a bit extense, cause it's a lot if timers.
public class mostraHorario extends Activity {
private ArrayList<String> Coimbra = new ArrayList<String>();

//classe para horario de coimbra
public class horaCoimbra{
    public String hora;
    public int destino;

    public horaCoimbra(String horaIn, int Destino){
        hora = horaIn;
        destino = Destino;
    }

    public void sethora(String horaInicial){
        hora = horaInicial;
    }

    public void setdestino(int refDestino){
        destino = refDestino;
    }
}

horaCoimbra horaC1, horaC2, horaC3, horaC4, horaC5, horaC6, horaC7, horaC8, horaC9, horaC10, horaC11, horaC12, horaC13, horaC14, horaC15, horaC16, horaC17, horaC18, horaC19, horaC20, horaC21, horaC22, horaC23, horaC24, horaC25, horaC26, horaC27, horaC28, horaC29, horaC30, horaC31, horaC32;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mostra_horario);

    TextView partida = (TextView) findViewById(R.id.partida);
    TextView destino = (TextView) findViewById(R.id.destino);

    Intent intent = getIntent();
    String Partida = intent.getStringExtra("Partida");
    String Destino = intent.getStringExtra("Destino");
    boolean Sabado = intent.getBooleanExtra("Sabado", true);
    boolean Domingo = intent.getBooleanExtra("Domingo", true);

    buildCoimbra();
    buildArray();

    partida.setText(Partida);
    destino.setText(Destino);

    //Aqui é o horario que vai aparecer
    if (Partida.equals("Coimbra")) {
        ListAdapter horarioAdapter = new costum_adapter(this, Coimbra);
        ListView horarioListView = (ListView) findViewById(R.id.horario_listView);
        horarioListView.setAdapter(horarioAdapter);
    }
}

public void buildCoimbra(){
    horaC1.sethora("7:15");
    horaC1.destino=9;
    horaC2.sethora("7:50");
    horaC2.destino=4;
    horaC3.sethora("8:25");
    horaC3.destino=9;
    horaC4.sethora("9:00");
    horaC4.destino=7;
    horaC5.sethora("10:00");
    horaC5.destino=7;
    horaC6.sethora("11:15");
    horaC6.destino=7;
    horaC7.sethora("11:25");
    horaC7.destino=3;
    horaC8.sethora("12:10");
    horaC8.destino=9;
    horaC9.sethora("12:25");
    horaC9.destino=3;
    horaC10.sethora("13:10");
    horaC10.destino=9;
    horaC11.sethora("14:05");
    horaC11.destino=7;
    horaC12.sethora("14:05");
    horaC12.destino=3;
    horaC13.sethora("15:15");
    horaC13.destino=9;
    horaC14.sethora("16:00");
    horaC14.destino=9;
    horaC15.sethora("16:15");
    horaC15.destino=7;
    horaC16.sethora("16:40");
    horaC16.destino=4;
    horaC17.sethora("17:10");
    horaC17.destino=6;
    horaC18.sethora("17:10");
    horaC18.destino=4;
    horaC19.sethora("17:15");
    horaC19.destino=5;
    horaC20.sethora("17:20");
    horaC20.destino=9;
    horaC21.sethora("17:40");
    horaC21.destino=9;
    horaC22.sethora("17:45");
    horaC22.destino=4;
    horaC23.sethora("18:00");
    horaC23.destino=6;
    horaC24.sethora("18:00");
    horaC24.destino=3;
    horaC25.sethora("18:15");
    horaC25.destino=6;
    horaC26.sethora("18:30");
    horaC26.destino=9;
    horaC27.sethora("18:45");
    horaC27.destino=3;
    horaC28.sethora("19:10");
    horaC28.destino=7;
    horaC29.sethora("19:10");
    horaC29.destino=3;
    horaC30.sethora("20:15");
    horaC30.destino=6;
    horaC31.sethora("21:45");
    horaC31.destino=6;
    horaC32.sethora("0:05");
    horaC32.destino=6;
}

public void buildArray(){
    Coimbra.add(horaC1.hora);
    Coimbra.add(horaC2.hora);
    Coimbra.add(horaC3.hora);
    Coimbra.add(horaC4.hora);
    Coimbra.add(horaC5.hora);
    Coimbra.add(horaC6.hora);
    Coimbra.add(horaC7.hora);
    Coimbra.add(horaC8.hora);
    Coimbra.add(horaC9.hora);
    Coimbra.add(horaC10.hora);
    Coimbra.add(horaC11.hora);
    Coimbra.add(horaC12.hora);
    Coimbra.add(horaC13.hora);
    Coimbra.add(horaC14.hora);
    Coimbra.add(horaC15.hora);
    Coimbra.add(horaC16.hora);
    Coimbra.add(horaC17.hora);
    Coimbra.add(horaC18.hora);
    Coimbra.add(horaC19.hora);
    Coimbra.add(horaC20.hora);
    Coimbra.add(horaC21.hora);
    Coimbra.add(horaC22.hora);
    Coimbra.add(horaC23.hora);
    Coimbra.add(horaC24.hora);
    Coimbra.add(horaC25.hora);
    Coimbra.add(horaC26.hora);
    Coimbra.add(horaC27.hora);
    Coimbra.add(horaC28.hora);
    Coimbra.add(horaC29.hora);
    Coimbra.add(horaC30.hora);
    Coimbra.add(horaC31.hora);
    Coimbra.add(horaC32.hora);
}

}
So here, Coimbra is the ArrayList, where i'm putting the timers to send to the ArrayList. And declare each timer as an object of the class cause i need for each one of them to have the destination atribute, so i can compare with the destitation selected by the user and remove the bus that don't go there.
It's giving me error on the "buildCoimbra();" line, and the sethora lines.

A: horaC1 = new horaCoimbra("7:15",9);
create objects of horaCoimbra like above

A: Each time bus times change you have to change, build and install your (updated) program. Your program should instead read the data from a file or database.


text:
Q: Javascript/node : Problem using pipe method from a readstream to a http response object I wanted to pass a text file's content to the server via the pipe method via the following code.
const {createServer}=require('http');
const {createReadStream}=require('fs');
let server=createServer((request,response)=>{
  response.writeHead(200,{'Content-Type':'text/plain'});
  let test=new Promise((resolve,reject)=>{
    try{let src=createReadStream('D:\\Javascript\\JavascriptPlayGround\\text.txt');}
    catch(err){reject(err);}
    resolve(src);
  })
  .then(src=>src.pipe(response)).then(xxx=>response.end('ended'))
  .catch(err=>console.log(err));
});
server.listen(8000);

But I get the following error
ReferenceError: src is not defined
    at D:\Javascript\JavascriptPlayGround\server.js:10:13

A: src does not exist in the scope where you try to resolve it. Also you should just pipe the file-stream to the response and not call end. Something like this should work:
const {createServer} = require('http');
const {createReadStream} = require('fs');
let server = createServer((request, response) => {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    let test = new Promise((resolve, reject) => {
        try {
            let src = createReadStream('D:\Javascript\JavascriptPlayGround\text.txt');
            resolve(src);
        } catch (err) {
            reject(err);
        }

    })
        .then(src => src.pipe(response))
        .catch(err => console.log(err));
});
server.listen(8000);

A: look on your Promise
let test=new Promise((resolve,reject)=>{
    try{
      let src=createReadStream('D:\\Javascript\\JavascriptPlayGround\\text.txt');
    }
    catch(err){
      reject(err);
    }
    resolve(src);
  })

You declare let src inside try block. When you leave the try block src became undefined.
Move your resolve into the try block
let test=new Promise((resolve,reject)=>{
    try{
      let src=createReadStream('D:\\Javascript\\JavascriptPlayGround\\text.txt');
      resolve(src);
    }
    catch(err){
      reject(err);
    }
  })


text:
Q: Characteristic and minimal polynomial of Jordan Block I was wondering what the characteristic and minimal polynomial of a single Jordan Block are?
My guess was that they are always equal to each other and that it is just the polynomial that is (where n=number of rows/colums) $(x -\lambda)^n$, correct?


text:
Q: how to pass values from extensions to AGI script and use that values in script extension to call php_agi
exten => 8380,n,AGI(php_falup.agi,${MSISDN},${var})

php_agiscript to grep values
<?
//require 'phpagi.php';
require('include/phpagi-2.20/phpagi.php');
$agi = new AGI();
$Variable =$agi->request[agi_arg_1,agi_arg_2];

I am trying this isthis currect.

A: You can access passed vars by
$var1=$argv[1];
$var2=$argv[2];


text:
Q: socket.io, vTiger, and csrf-magic.js. CORS issues I'm attempting to create and add a socket.io module to my vTiger 7.0 so that I can update fields in real-time to multiple users.
We are have issues with users changing fields that should be locked while our quality control is attempting to check the record. This is causes things to get approved that should not. Node.js with vTiger will be awesome add-on.
The only problem is that vTiger uses csrf-magic.js to create a token that need to be included in the header to allow CORS
I have the middleware setup in my node project to allow my vtiger to make a request
vTiger is on vtiger.example.com
The node server is on node.example.com:3010
//server code node.example.com:3010
const fs = require("fs");
const config = require("./core/config").config();
var options = {
    key: fs.readFileSync(config.key),
    cert: fs.readFileSync(config.cert),
    ca: fs.readFileSync(config.ca),
    requestCert: true,
    rejectUnauthorized: false,
};

const app = require("express")();
const server = require("https").Server(options, app);
const io = require("socket.io")(server);
// Need to send io to socket module

module.exports = io;
app.use(function (req, res, next) {
    var allowedOrigins = [
        "https://node.example.com",
        "https://vtiger.example.com"
    ];
    var origin = req.headers.origin;
        if (allowedOrigins.indexOf(origin) > -1) {
        res.setHeader("Access-Control-Allow-Origin", origin);
    }

    res.header("Access-Control-Allow-Methods", "GET, OPTIONS");
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
    res.header("Access-Control-Allow-Credentials", true);

    return next();
});

io.sockets.on("connection", require("./sockets/socket.js"));

const qc = require('./models/qc_model');
app.get('/', (req,res) => {
    res.json({message: 'No Access'});
})

qc.pullLeadInfo(13622196, 10730, (data) => {
    console.log(data.lead.lsloa_ver_by);
});

//Start the server
server.listen(config.port, () => {
    console.log("server listening on port: " + config.port);
});

\\client side vtiger.example.com
var socket = io.connect('https://node.example.com:3010');

I get this error
Access to XMLHttpRequest at 'https://node.example.com:3010/socket.io/?EIO=4&transport=polling&t=NmEEc_r' from origin 'https://vtiger.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
csrf-magic.js:41 GET https://node.example.com:3010/socket.io/?EIO=4&transport=polling&t=NmEEc_r net::ERR_FAILED

I cannot find any good documentation dealing with this issue. Any help would be great!

A: Found the information here
https://github.com/socketio/socket.io/issues/3929

// Server

io.engine.on("headers", (headers) => {
  headers["Access-Control-Allow-Private-Network"] = true;
});

// Client

const socket = io({
  extraHeaders: {
    "Access-Control-Request-Private-Network": true
  }
});


text:
Q: Unable to load S3 parquet with postgresql driver in spark-shell I am trying to load parquet file from in EMR spark-shell.
Command:
// to start spark
spark-shell  --driver-class-path postgresql-42.2.5.jar --jars postgresql-42.2.5.jar
// to read data
spark.read.parquet("s3://file_location/").write.saveAsTable("table_name")

Error:
19/04/11 10:08:41 WARN FileStreamSink: Error while looking for metadata directory.
java.lang.RuntimeException: java.lang.ClassNotFoundException: Class com.amazon.ws.emr.hadoop.fs.EmrFileSystem not found
  at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2195)
  at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2702)
  at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2715)
  at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:93)
  at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2751)
  at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2733)
  at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:377)
  at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
  at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:350)
  at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:348)
  at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
  at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
  at scala.collection.immutable.List.foreach(List.scala:381)
  at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
  at scala.collection.immutable.List.flatMap(List.scala:344)
  at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:348)
  at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:178)
  at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:559)
  at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:543)
  ... 48 elided
Caused by: java.lang.ClassNotFoundException: Class com.amazon.ws.emr.hadoop.fs.EmrFileSystem not found
  at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:2101)
  at org.apac

*

*when I am running spark-shell without postgresql jar, i am able to load data from s3.

Any help would be appreciated.


text:
Q: How to stop gesture detector from executing long press on a single tap when item is clicked in recyclerview? Before you mark this question as duplicate please note that I have looked at all solutions to similar questions here on Stackoverflow and they did not work.
Below is the process in which I implemented the gesture detector. You'll see that in the private class which extends GestureDetector.SimpleOnGestureListener, I have only created code for a long press, yet the code contained in onLongPress also fires on a single tap.
Class implements OnItemTouchListsner see code below
public class MyFragment extends Fragment implements RecyclerView.OnItemTouchListener

I create a private variable see code below
private GestureDetectorCompat gestureDetector;

I assign gestureDetector in onCreateView see code below
gestureDetector = new GestureDetectorCompat(getActivity().getApplicationContext(), new RecyclerViewOnGestureListener());

I implement required methods for OnItemTouchListener see code below
@Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            gestureDetector.onTouchEvent(e);
            return false;
        }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {

    }

I create a private class for the gesture listener see code below
private class RecyclerViewOnGestureListener extends GestureDetector.SimpleOnGestureListener {

            @Override
            public void onLongPress(MotionEvent e) {
                //code in here executes on single tap, but should only execute on long press
                super.onLongPress(e);
            }
        }

A: Trying overriding RecyclerView#requestDisallowInterceptTouchEvent and cancel it there.

A: What caused problem
I was using RecyclerItemClickListener (see link to github page) and because of this I could not use longpress, as the code within longpress needed to be executed inside a fragment.
So I had my fragment implement OnItemTouchListener and set recyclerview.addOnItemTouchListener(this). I only included the code for a long press within my fragment. I had also set recyclerview.addOnItemTouchListener to RecyclerItemClickListener.
What caused problem: setting onItemTouchListener for recyclerview twice.
Solution: make RecyclerItemClickListener an inner class.


text:
Q: An error (Call to a possibly undefined method echo through a reference with static type) when a calling a class method of an object I have a structure with PluginMediator class and ServiceProxy class. They both are within the same namespace and when I am creating an object of the proxy class and try to invoke each of its methods I receive the following error:

Call to a possibly undefined method echo through a reference with
  static type

Fla code
var _proxy:MyServiceProxy = new MyServiceProxy();

// calls MyService to echo a string and return to onHelloResult.
_proxy.echo("Hi", onHelloResult, null);
_proxy.echo("world!", onHelloResult);

MyServiceProxy class
public class MyServiceProxy extends BaseProxy
{
    public function echo(message:String, callback:Function = null, context:Object = null):void
    {
        callService("echo", [message], callback, context);
    }
}

A: I found the problem. Because I am not quite familiar with services and vsphere(flash) sdk, I renamed the class without the word Mediator. Once I returned the word in the name, everything just went fine. For now;)


text:
Q: What is best practice for setting font size based on device? I am attempting to scale my app's font size based on the device being used.  What is best practice for doing this?

A: Your best option is to actually take advantage of the dynamic text features added in iOS 7. That way your user is actually in charge of the font size and your app adjusts as needed. This will give your users who have poor eyesight the best experience.


text:
Q: Text string from table add to select option with jquery I have select with some option:
<select class="mat">
    <option value="0">mat 1</option>
</select>

and table:

        option 1
        desc

        option 2
        desc

        option 3
        desc

I want with jquery copy text 'option 1', 'option 2' from this table to select option  and get this:
<select class="mat">
    <option value="0">option 1</option>
    <option value="1">option 2</option>
    <option value="2">option 3</option>
</select>

A: Try this:
$('#mat-table td:first-child').each(function(i) {
    var $option = $('<option>', { value: i }).text(this.textContent);
    $('.mat').append($option);
});

See Fiddle

A:

$(document).ready(function(){
  $('.mat').html('');
  var i = 0;
  $("#mat-table tr").each(function(){
    $('.mat').append($('<option>', {
      value: i,
      text: $(this).find('td:nth-child(1)').html()
    }));
    i++;
  });
});

<select class="mat">
  <option value="0">mat 1</option>
</select>

    option 1
    desc

    option 2
    desc

    option 3
    desc


text:
Q: using blob or base64 which is more efficient for uploading we are using cropit for cropping image at client side then uploading base64 string to server ,
but some time for large images it crashes mobile browsers with low ram ,
is it good idea to convert base64 to blob [Creating a BLOB from a Base64 string in JavaScript then upload that on server or it will effect more mobile users as first image will be covered to based64 for cropping and then back to blob .

A: Base64 encoding takes up about a third more space than the original data. It was designed to safely send data through text (e.g. in mail bodies).
You're better off using the binary image, as it will be smaller and so quicker to upload.
Go with BLOB, mate.


text:
Q: Examples of Sobolev Spaces I would like to apologize in advance for this trivial question!
Does constant functions $u \equiv C$ and, in partucular, $u \equiv 0$ belong to $W_{0}^{1,2}(\Omega)$?
Update 2:
$\Omega \subset \mathbb{R}^n$ is bounded open set.
I wonder whether $\exists \{u_i\}_{0}^{\infty} \subset C_{0}^{\infty},\mbox{ such that } u_i \rightarrow u \mbox{ in } W^{1,2}$?

A: Q1. Non-zero constant functions DO NOT BELONG to $W_0^{1,2}(\Omega)$.
Q2. The space $W_0^{1,2}(\Omega)$ is defined as the «completion» of $C_0^\infty(\Omega)$ with norm
$$
\|u\|_{W^{1,2}_0(\Omega)}=\left(\int_\Omega\big(u^2(x)+\big|\nabla u(x)\big|^2\big)\,dx\right)^{1/2}.
$$
Thus, indeed, every element of $W_0^{1,2}(\Omega)$ can be $\|\cdot\|_{W^{1,2}_0(\Omega)}-$approximated by functions in
$C_0^\infty(\Omega)$, even if $\Omega$ is unbounded.

A: You can characterize $W^{1,2}_0$ as "the 'compactly supported' $L^2$ functions that have $L^2$ weak derivatives." Since the weak derivatives of a constant function are all zero, hence $L^2$, the answer to your question is the answer to, "are constant functions compactly supported $L^2$?" This is never true unless the constant is zero.


text:
Q: Bad comportement while check error during makefile I want to make automatically the documentation of my project with my makefile.
I also create a target doc (and a variable DOC_DIRECTORY = ../doc) to specify the directory of the documentation. In my doxygen file, I added a log file name "doxyLog.log" in the ../doc/ directory.
Here is my target definition :
#Creation of the Doxygen documentation
doc: $(DOC_DIRECTORY)/path_finder_doc
    doxygen $(DOC_DIRECTORY)/path_finder_doc
    @echo $(shell test -s ../doc/doxyLog.log; echo $$?)
ifeq ($(shell test -s ../doc/doxyLog.log; echo $$?),1)
    @echo "Generation of the doxygen documentation done"
else
    @echo "Error during the creation of the documentation, please check $(DOC_DIRECTORY)/doxyLog.log"
endif

To test if my check is working, I manually introduce an error in my documentation (a bad command like \retufjdkshrn instead of \return). But, when I launch the make doc, this error appears after the second time :
First make doc (with an error in the doc ) --> Generation of the doxygen documentation done
Second make doc (always the error in the doc) --> Error during the creation of the documentation, please check ../doc/doxyLog.log
I don't understand why, can someone help me please?

A: There appear to be two things wrong here, so parts of this answer must be guesswork.
First:
ifeq ($(shell test -s ../doc/doxyLog.log; echo $$?),1)
    @echo "Generation of the doxygen documentation done"

As I understand test, it will return 0 if the file exists and 1 if the file does not exist. I suspect that you didn't test this before putting it into your makefile.
Second, you are confusing shell commands with Make commands. This:
ifeq ($(shell test -s ../doc/doxyLog.log; echo $$?),1)
    @echo "Generation of the doxygen documentation done"
else
    @echo "Error..."
endif

is a Make conditional. Make will evaluate it before running any rule. Since the log file does not yet exist, the shell command will return 1 (see First), the conditional will evaluate to true and the entire if-then-else statement will become
    @echo "Generation of the doxygen documentation done"

This will become part of the rule before the rule is executed. On the next pass, the file already exists, the shell command returns 0 and the the statement becomes
    @echo "Error..."

This explains why you're getting strange results.
If you want Make to report on the results of the attempt it's just made, you must put a shell conditional in a command in the rule:
doc: $(DOC_DIRECTORY)/path_finder_doc
    doxygen $(DOC_DIRECTORY)/path_finder_doc
    @if [ -s ../doc/doxyLog.log ]; then echo Log done; else echo error...; fi


text:
Q: Using Isotope with imagesLoaded for Ajax loaded content I'm using Isotope to create a masonry grid and I've implemented a load more button that fetches more items when clicked with AJAX.
In my AJAX success function I create the needed html for the grid item like so:
 htm = '';
 htm+= '
';
 htm+= '';
 htm+= '
';

And after that I append the element to a container and call a redo_isotope function
$container.append(htm);
redo_isotope()

My redo_isotope function:
  var $container = $('.grid');
  function redo_isotope(){
     $container.imagesLoaded( function(){
       $container.isotope({
         itemSelector: '.grid-item',
         transitionDuration:0,
         masonry: {
          gutter:15
         },
       });
     });
    $container.isotope().isotope('reloadItems');
  }

In most of the cases this makes the newly appended items layout nicely on the page without causing any overlapping issues, but in some of the cases the imagesLoaded function doesn't seem to fire properly causing the height of the appended items to be miscalculated and cut off.
Has anyone experienced a similar problem and in that case how did you solve it?

A: Here's my suggestion:
1º append the content to the $container:
var htm = '

';
$container.append( $(htm) );

2º call the isotope appended function:
$container.isotope( 'appended', $(htm) );

3º monitor the progress of the imagesLoaded() function ... & ...
4º trigger the isotope layout function everytime a image is loaded:
$container.imagesLoaded().progress(function(){
    $container.isotope( 'layout' );
});


text:
Q: How to create a hierarchy ID I'd like to make a method to generate a hierarchy ID like the following

1.0
 1.1
   1.1.1
   1.1.2
   1.1.3

 1.2
 1.3
2.0
 2.1

is there and way to accomplish this ?
any help will be highly appreciated.

A: Here is my quick attempt.
I am assuming that instead of 1.0 and 2.0 you meant just 1 and 2, respectively, as otherwise it would be inconsistent.
public class HierarchyGenerator
{
    private List<int> levels = new List<int> { 1 };

    public void DownOneLevel()
    {
        levels.Add(1);
    }

    public void UpLevels(int numLevels)
    {
        if (levels.Count < numLevels + 1)
            throw new InvalidOperationException(
                "Attempt to ascend beyond the top level.");

        for (int i = 0; i < numLevels; i++)
            levels.RemoveAt(levels.Count - 1);
        MoveNext();
    }

    public void MoveNext()
    {
        levels[levels.Count - 1]++;
    }

    public string Current
    {
        get
        {
            return new string(' ', (levels.Count - 1) * 2)
                 + string.Join(".", levels.Select(l => l.ToString()));
        }
    }
}

static partial class Program
{
    static void Main()
    {
        var hg = new HierarchyGenerator();
        Console.WriteLine(hg.Current);  // 1
        hg.DownOneLevel();
        Console.WriteLine(hg.Current);  // 1.1
        hg.DownOneLevel();
        Console.WriteLine(hg.Current);  // 1.1.1
        hg.MoveNext();
        Console.WriteLine(hg.Current);  // 1.1.2
        hg.MoveNext();
        Console.WriteLine(hg.Current);  // 1.1.3
        hg.UpLevels(1);
        Console.WriteLine(hg.Current);  // 1.2
        hg.MoveNext();
        Console.WriteLine(hg.Current);  // 1.3
        hg.UpLevels(1);
        Console.WriteLine(hg.Current);  // 2
        hg.DownOneLevel();
        Console.WriteLine(hg.Current);  // 2.1
    }
}

A: I'll assume that your hierarchy is expressed like a tree using this class:
class Node {
  public Node() { Children = new Node[0]; }
  public String Name { get; set; }
  public IEnumerable<Node> Children { get; set; }
}

You can then visit each node in the tree using this method:
void Visit(Node node, Stack<Int32> levels, Action<Node, String> nodeAction) {
  // Generation of hierachyId can be customized here to say use letters.
  var hierarchyId =
    String.Join(".", levels.Reverse().Select(l => l.ToString()).ToArray());
  nodeAction(node, hierarchyId);
  var i = 1;
  foreach (var child in node.Children) {
    levels.Push(i++);
    Visit(child, levels, nodeAction);
    levels.Pop();
  }
}

This code will visit each node in the tree in a depth first order including the root. However, the root will have an empty hierarchyId. To start visiting the tree use this code:
Visit(
  root,
  new Stack<int>(),
  (node, hierarchyId) => Console.WriteLine(hierarchyId + ": " + node.Name)
);

The action will simply write the node name and generated hierarchy id to the console.
Here are some sample data:
var root = new Node {
  Name = "Root",
  Children = new[] {
    new Node {
      Name = "A",
      Children = new[] {
        new Node {
          Name = "AA",
          Children = new [] {
            new Node { Name = "AAA" },
            new Node { Name = "AAB" },
            new Node { Name = "AAC" }
          }
        },
        new Node { Name = "AB" },
        new Node { Name = "AC" }
      }
    },
    new Node {
      Name = "B",
      Children = new Node[] {
        new Node { Name = "BA" }
      }
    }
  }
};

Running the code on this tree writes the following to the console:
: Root
1: A
1.1: AA
1.1.1: AAA
1.1.2: AAB
1.1.3: AAC
1.2: AB
1.3: AC
2: B
2.1: BA


text:
Q: How to set a image selection limit using intent in kotlin I want to select only 5 images from the gallery. Here I shared my code. Can anyone help?
val intent = Intent(Intent.ACTION_GET_CONTENT)
// var intent = Intent(Intent.CATEGORY_APP_GALLERY)
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
intent.action = Intent.ACTION_GET_CONTENT
intent.putExtra(Intent.CATEGORY_APP_GALLERY,true)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"

startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_MULTIPLE)


text:
Q: JWT token encryption and transferring in http get I'd like to validate one security approach that we'd like to use.
We have a two applications and we'd like to pass data using jwt token (make redirect from one pllication to another + pass sensitive information in token).
For this purpose we  created JWTSigner with shared secret and sign all claims.
JWTSigner signer = new JWTSigner(secret);
return signer.sign(claims);

As per my understanding preferable we need additionally encrypt this information as signing pervent us only from tampering this info.
The question is whether it's secure enough to pass this token as parameter in url ?

A: It depends.
If done right, yes, it is safe -- as only your applications will be able to issue valid tokens. If done wrong, it is worthless.
How to do it right (TM):

*

*The payload in JWT is not generally encrypted; it can be read by third parties after base64-decoding. Signing it prevents tampering, but not disclosure.

*JWT has an "alg" field that can be used to specify the encryption algorithm used. It is attacker-friendly: do not trust its contents.

*Make yourself immune to replay attacks, for example by using and verifying a request counter or a time-stamp.

*Use strong encryption. Public-key encryption has the advantage of allowing each endpoint to verify the other, even without knowing the other's private key; but symmetric encryption is also an option.

*Protect your secret keys. Use different keys for testing and deployment, and never check keys into source-control.


text:
Q: A3 Drawing Template I'm trying to create a method/workflow for the batch creation of A3 drawings using LaTeX.
I issue drawings that look like this:

Most of the information on the right never changes, only the Title, Drawing No. and Revision No. On the left there's two pictures, each with a short description underneath.
There are a set number of these drawings that we use and typically I issue only some of them for any one project. The drawings must be A3 size.
What I'm trying to build is likely a LaTeX main file into which I can write all the info that will be the same for each drawing e.g.

*

*Project

*Project Number

*Date

*Issuer

*etc

And then a command that adds a drawing to the document in a customisable way based on input commands e.g:
\addDrawing{Drawing_Number, Drawing_Revision, Thing1_Title, Thing1_text, Thing1_image, Thing2_Title, Thing2_text, Thing2_image}

To begin with, I please need help creating this drawing template in LaTeX. I have tried using the 'standalone' class, but abandoned it because I didn't think it's the right class for this. I then used 'tikzposter' but it doesn't do A3 (as far as I could figure out) so I dropped that.
I'd appreciate any input as to the best way to create these drawing templates and how to add the pictures and text for "Thing1" and "Thing2"
Many thanx in advance.

A: Since posting, I've come up with the following method solution. I made the drawing template in inkscape, import it and add text over in latex using Tikz.
Here's the blank template.

And an example where I just add a title.
\documentclass[preview]{standalone}
\usepackage[a1paper]{geometry}
\usepackage{tikz}

% Define commands
\newcommand{\drawing}{}
\newcommand{\drawingTitle}{}

\newcommand{\makeDetail}[2]{
    \renewcommand{\drawing}{#1}
    \renewcommand{\drawingTitle}{#2}

    \begin{tikzpicture}
        \node[anchor=south west, inner sep=0] at (0,0) {\includegraphics{\drawing}};
        \node[anchor=south west, inner sep=0] at (35.8,5.8) {\huge{\drawingTitle}};
    \end{tikzpicture}
}

\begin{document}

     \makeDetail{drawing_example}{A Name Here}

\end{document}

The result is:

I admit, it is not the most elegant solution. Placing the text correctly and matching the font and font size is a bit of a pain, but I reckon I only have to go through that process once.
Using the same method, I can then add Thing1 and Thing2 as required.


text:
Q: Loading dynamic images on an bootstrap modal with ajax I/m trying to load dynamic images on a bootstrap modal with ajax when a user clicks on different links on a page. Each link has an data-id that is used to show its relevant image in the modal body. It works fine for the first couple of links but starts to misbehave after 4-5 clicks. Later it starts showing previously loaded images when a link is clicked and the relevant image is shown after several seconds of the modal being triggered. Can anyone help me what I'm doing wrong with my code below:
My JS Code:
$(document).ready(function(){
    $(document).on('click', '.viewPhoto', function(e){
        e.preventDefault();
        var pid = $(this).data('id');   // it will get id of clicked row

        $("#photoContent").html("Please Wait...");

        $.ajax({
            url: "URL OF PAGE",
            type: 'POST',
            data: 'pid='+pid,
        })
        .done(function(data){
            $('#photoContent').html(data); // load response
        })
        .fail(function(){
            $('#photoContent ').html('Error');
        });

    });
});

And my modal HTML is:

       <button type="button" class="close" data-dismiss="modal">×
           </button>

        <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>

And the HTML of Link is:
View Image

A: you should use cache: false in your ajax command.


text:
Q: What method would you recommend to make Operating System API calls in a cross-platform library you are building? Let me explain further ..
Is it advisable to use , something like :
#ifdef _WIN32
void someFunction()
{
   // windows version  of the function which makes Windows API Calls
}
#elif defined(__linux__)
void someFunction()
{
   // linux version of the function which makes POSIX calls
}
#endif

OR  create separate source code files for each operating systems, and then use conditional codes in makefiles or any build tools to compile the source code based on the operating system ???

A: First of all, "best" is at some level opinion-based and might get this question closed. However, my view is that you should work from a standpoint that there is one set of Portable Operating System Interfaces (+X), and that these are what you code to. Then, for systems that lack some or all of the portable interfaces, you can provide drop-in replacement implementations built on top of whatever OS-specific interfaces the particular oddball operating system wants you to use.
This allows you to keep complex conditionals and OS-specific logic out of your actual program logic, and isolate it all as platform-support shims. Some people prefer to do this by building their own portability layer (APR, NSPR, etc.) and treating POSIX just as one of the backends for it. I strongly recommend against doing this, since:

*

*It imposes significant levels of overhead on systems that already have a portable interface.

*It makes your code hard to read by people who know the standard interfaces but who aren't familar with your own portability layer.

*It makes your code hard to reuse in projects where your portability layer isn't a good fit.

*It's a huge rabbit hole of yak-shaving that will bog you down and take all your time away from whatever you actually wanted to code.


text:
Q: {Рython}Почему выдает ошибку, по типу этот объект нельзя вызвать('module' object is not callable)? Я знаю что нельзя вызвать модуль который заимпортил, но так сказано в доках + раньше у меня работало. С тех пор я ничего не менял! Ошибка в 6 строке('module' object is not callable)

A: from InstagramAPI import InstagramAPI

и потом уже вызывай, класс лежит в модуле
можешь также вызвать InstagramAPI.InstagramAPI()


text:
Q: DataTable pagination does not work I'm use DataTable to display my data by serverSide mode and ajax.
Everything is okay, but pagination doesn't work.

You can review the codes as follow:
HTML:

            ID
            First name
            Last name
            Email

Javascript:
$(document).ready(function () {
    $('#table').DataTable({
        serverSide: true,
        ajax: {
            url: '<?php echo base_url(); ?>folder/class/method'
        },
        processing: true,
        scrollY: 370,
        paging: true,
        bJQueryUI: true
    });
});

The data that returned from server (JSON) as following:
{
    "draw": 1,
    "recordsTotal": 1208,
    "recordsFiltered": 10,
    "data": [
        ["1", "pando", "rewar", "pando@hotmail.com"],
        ["2", "chori", "raon", "m_chori@hotmail.com"],
        ["3", "Gorbat", "horiz", "horiz_555@yahoo.com"],
        ["4", "martin", "sokza", "martin_em5@gmail.com"],
        ["5", "dooz", "solda", "solda_m@gmail.com"],
        ["6", "maro", "meza", "r_meza@hotmail.com"],
        ["7", "nod", "ion", "nod_eam@yahoo.com"],
        ["8", "kaz", "loob", "kaz_007@hotmail.com"],
        ["9", "Barbara", "Elliott", "adipiscing@nonmassanon.org"],
        ["10", "Kendall", "Nathaniel", "ante.blandit@scelerisque.edu"]
    ]
}

All components of DataTable work fine, but the pagination not.

A: Parameter recordsFiltered must be equal to recordsTotal unless user performed a search. See manual for more information on sent and received parameters.
Also make sure you're returning the same value of draw parameter in the response.  In JSON response value of draw parameter must match value of draw parameter from the request.


text:
Q: ModuleNotFoundError: No module named 'plyer.platforms' when EXE created by pyinstaller runs plyer.filechooser.open_file() and choose_dir() My python script with kivy GUI runs smoothly in Pycharm or Spyder IDE. After creating the EXE (Windows) using pyinstaller, the EXE can run with the GUI appearing without any issues. However when I click buttons that run plyer.filechooser.open_file() or plyer.filechooser.choose_dir(), this error appears:
 Traceback (most recent call last):
   File "plyer\utils.py", line 96, in _ensure_obj
 ModuleNotFoundError: No module named 'plyer.platforms'
[INFO   ] [Base        ] Leaving application in progress...

I just realized that the output directory created by pyinstaller under "dist" directory contains the used packages in my script such as pandas, numpy, pyexcelerate etc. but NOT plyer. That is strange because my script has explicitly import plyer at the beginning.
My spec file for pyinstaller is shown below. The reason I'm using plyer to select files is because of its small size whereas PyQt5 creates huge EXE size while kivy FileChooser does not show all hard drives available in a user's computer (if anyone knows solution for this would be great).
import os
from os.path import join

from kivy import kivy_data_dir
from kivy.deps import sdl2, glew
from kivy.tools.packaging import pyinstaller_hooks as hooks

block_cipher = None
kivy_deps_all = hooks.get_deps_all()
kivy_factory_modules = hooks.get_factory_modules()

# list of data filepath (your *.kv, image files, kivymd files) to copy to the output directory
datas = [('./gui.kv', '.'),
         ('./venv/Lib/site-packages/kivymd', 'kivymd')
        ]

# list of modules to exclude from Analysis
excludes_a = ['Tkinter', '_tkinter', 'twisted', 'docutils', 'pygments']

# list of hiddenimports
hiddenimports = kivy_deps_all['hiddenimports'] + kivy_factory_modules

# binary data
sdl2_bin_tocs = [Tree(p) for p in sdl2.dep_bins]
glew_bin_tocs = [Tree(p) for p in glew.dep_bins]
bin_tocs = sdl2_bin_tocs + glew_bin_tocs

# assets
kivy_assets_toc = Tree(kivy_data_dir, prefix=join('kivy_install', 'data'))
# source_assets_toc = Tree("images", prefix="images")
# assets_toc = [kivy_assets_toc, source_assets_toc]
assets_toc = [kivy_assets_toc]

tocs = bin_tocs + assets_toc

a = Analysis(['main.py'],
             pathex=[os.getcwd()],
             binaries=None,
             datas=datas,
             hiddenimports=hiddenimports,
             hookspath=[],
             runtime_hooks=[],
             excludes=excludes_a,
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe1 = EXE(pyz,
           a.scripts,
           name='main',   # name of output *.exe file
           exclude_binaries=True,
           # icon=join('images', 'mywinapp.ico'),
           debug=False,
           strip=False,
           upx=True,
           console=True)  # set to console-based, NOT window-based.

coll = COLLECT(exe1,
               a.binaries,
               a.zipfiles,
               a.datas,
               *tocs,
               strip=False,
               upx=True,
               name='Parser')

A: I also had the same issue.
My fix was to add the following argument while creating the exe with pyinstaller
--hidden-import plyer.platforms.win.notification

A: add following hidden import to spec file
a = Analysis(
   ...
   hiddenimports=['plyer.platforms.win.filechooser'],
   ...

A: The problem is caused by missing hidden imports. Try to include "platform-specific module" like brsaylor did in Windows notification - NotImplementedError: No usable implementation found! #485:
https://github.com/kivy/plyer/issues/485#issuecomment-457880444

I was having a similar issue with the FileChooser on macos, and I solved it by adding the platform-specific module to hiddenimports in the spec file. For this issue, the change would be something like:
a = Analysis(
   ...
   hiddenimports=['plyer.platforms.win.notification'],
   ...


text:
Q: ¿Cómo acceder desde javascript a un element ul li cuanto tengo varios con sql?     echo "
";
$conexion=mysqli_connect("***", "***", "***", "***");

if(!$conexion){
    echo "La conexion ha fallado : " . mysqli_error();
    exit();
}

$tamano_paginas=6;

if(isset($_GET["pagina"])){
    if($_GET["pagina"]==1){
        header("Location: index.php");
    }else{
        $pagina=$_GET["pagina"];
    }
}else{
    $pagina=1;
}

$empezar=($pagina-1)*($tamano_paginas);

$consulta="SELECT * FROM contenidoblog";

if($resultado=mysqli_query($conexion, $consulta)){

    $num_filas=mysqli_num_rows($resultado);
    $total_paginas=ceil($num_filas/$tamano_paginas);
}

$consulta_filtrada="SELECT * FROM contenidoblog LIMIT $empezar, $tamano_paginas";
$resultado1=mysqli_query($conexion, $consulta_filtrada);

    if($resultado1){

        while($registro= mysqli_fetch_assoc($resultado1)){
            echo "

Favoritos

Compartir

Me gusta

Comentar

";
            echo "
 ";

            if($registro['imagen']!=""){
                echo "";
            }

            echo"

            ";
            echo "
 ". $registro['fecha'] ."
";
            echo "
" . $registro['cabecera'] . "
";
            echo "
". $registro['titular'] . "
";

            echo "";
            echo "
";

            echo "
";

        }

    }

    mysqli_close($conexion);

    for($i=1;$i<=$total_paginas;$i++){
        echo "" . $i . "  ";
    }
    echo "

";

echo "
";

El script es éste:
$(document).ready(function(){

$("#contenedor_central .boton_opciones").click(function(e){
        e.preventDefault();
        $("#contenedor_central .menu_noticia").addEventListener;
         if ($(this).hasClass('desactivado')){
             alert("HEY");
            $(this).css({"display":"table"});
            $(this).removeClass('desactivado');
            $(this).addClass('activado');
         }else{
            $(this).removeClass('activado');
            $(this).css({"display":"table"});
            $(this).removeClass('activado');
            $(this).addClass('desactivado');
         }
    });
 });

El problema está en que cuando le doy al icono para mostrar el ul, se me muestran todos los ul de todos los divs, y yo solo quiero que se muestre el que he clicado

A: Lo que yo haría sería añadir un padre para cada elemento menu_noticia y cajaContenedor, con el fin de que puedan ser hermanos directos sin que interfieran el resto de elementos y poder hacer un script que detecte cual es el ul que pertenece a la "familia" de elementos del botón al cual se le dio click

Favoritos

Compartir

Me gusta

Comentar

$(document).ready(function(){
    $("#contenedor_central .boton_opciones").click(function(e){
        e.preventDefault();

        var elemento = $(this).parents('.contenedor_item').find('.menu_noticia');

        $(elemento).css({"display":"table"});

        if ($(elemento).hasClass('desactivado')){
             alert("HEY");
            $(elemento).removeClass('desactivado');
            $(elemento).addClass('activado');
        }else{
            $(elemento).removeClass('activado');
            $(elemento).removeClass('activado');
            $(elemento).addClass('desactivado');
        }
    });
});

A: Hay dos maneras de hacerlo. La más fácil, a mi gusto, es que cada uno de tus elementos cajaContenedor tenga su propio ul de opciones. De esa manera, al activar .boton_opciones puede dirigirse a su propio "hermano" (en el sentido que pertenecen al mismo parent).
En el siguiente ejemplo reemplacé algunos IDs por clases porque en tu código estarías repitiendo IDs por cada resultado y eso es incorrecto. Me tomé la libertad de ponerle algunos estilos.

      $(document).ready(function(){

        $("#contenedor_central .boton_opciones").click(function(e){
          // acá el botón opciones encuentra el "menú noticia" de su mismo contenedor.
          var $menu_noticia= jQuery(this)
          .closest('.cajaContenedor')
          .find('.menu_noticia');

          if ( $menu_noticia.hasClass('desactivado')){
              $menu_noticia
                .removeClass('desactivado')
                .addClass('activado');
           }else{
               $menu_noticia
                .removeClass('activado')
                .addClass('desactivado');
           }
        });
      });
#contenedor_central {
        width:100%
        height:100%;
        border:; 1px solid red;
      }
      .cajaContenedor {
        border-bottom: 1px solid;
        margin-bottom:10px;
        width:40%;
        height:auto;
        margin-left:30%;
        display: flex;
        float:left;
      }
      .cajaContenedor h2 {
        font-family: Georgia,Times,Times New Roman,serif;
        text-align:left;
        color:blue;
      }
      .fecha {
        text-align:left; margin-top:0px;
      }
      .contenedor_titular_cabecera {
        padding-left:4px; float:left; display:block; width:100%;
      }
      .menu_noticia {
        position:absolute;
        display:none;
      }
      .menu_noticia.activado {
        display:table;
      }
      .titular {
        font-size:18px;
        font-family: Georgia,Times,Times New Roman,serif;
        font-size: 15px;
        text-align:left;
        color:#707070;
      }
      .opciones {
        position:relative;
        float:right;

      }
      .boton_opciones {
        float:right;
      }
      .arrow-down {
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-top: 8px solid #f00;
        display:inline-block;
        margin-bottom:0;
      }

           Opciones

Favoritos

Compartir

Me gusta

Comentar

fecha1

titulo1

Contenido 1

           Opciones

Favoritos

Compartir

Me gusta

Comentar

fecha2

titulo2

Contenido 2

Tendrías que adaptar el html de tu script PHP para generar ese tipo de bloques HTML.
Hay otra opción en donde agregas sólo un bloque de .menu_noticia (y esto se haría afuera del loop while) y al pinchar en .menu_opciones inserta temporalmente el bloque .menu_noticia dentro del contenedor que acabas de pinchar. Pero como las opciones para actuar sobre cada post estarían vinculadas a su ID, además de modificar el DOM tendrías que modificar los links asociados a Favoritos, Compartir, etc al momento de meter ese contenedor en el contenedor del artículo. Puede que esto sea sobreoptimizar.

A: Para seleccionar el objeto al que se le ha dado click con jquery, puedes hacerlo de la siguiente forma:

window.addEventListener('click', clickHandler, false);

function clickHandler(e) {

  var tg = $(e.target);

  if ( tg.hasClass('boton_opciones') ) { // o como identifiques lo que quieres
    if (tg.hasClass('desactivado')) {
      // Lo activas, etc...
    } else {
      // Lo desactivas, etc...
    }
  }
}


text:
Q: beginner attempting to read xml into php I have an xml feed located here that I am trying to read into a php script, then cycle through the <packages>, and sum the <downloads>.  I've attempted to do this using DOMDocument, but have thus far failed.
the basic method i've been trying to use is as follows
<?php
$dom = new DomDocument;
$dom->loadXML('http://www.phogue.net/feed');
$packages = $dom->getElementsByTagName('package');
foreach($packages as $item)
{
    echo $item->getAttribute('uid').'<br>';
}
?>

The above code is meant to just print out the name of each item, but its not working.  I am currently getting the following error
Warning: DOMDocument::loadXML() [domdocument.loadxml]: Start tag expected, '<' not found in Entity, line: 1 in /home/a8744502/public_html/userbar.php on line 3
WORKING CODE:
<?php
$dom = new DomDocument;
$dom->load('http://www.phogue.net/feed/');
$package = $dom->getElementsByTagName('package');
$value=0;

foreach ($package as $plugin) {

    $downloads = $plugin->getElementsByTagName("downloads");
    $download = $downloads->item(0)->nodeValue;

    $authors = $plugin->getElementsByTagName("author");
    $author = $authors->item(0)->nodeValue;
    if($author == "Zaeed")
    {
        $value += $download;
    }
}
echo $value;
?>

A: DOMDocument::loadXML() expects a string of XML. Try DOMDocument::load() instead - http://www.php.net/manual/en/domdocument.load.php
Keep in mind that to open an XML file via HTTP, you will need the appropriate wrapper enabled.

A: You have a open parenthesis at the beginning of your echo.


text:
Q: Sort both values in a multidimensional Im wokring on a bit of functionality that works a lot with multidimensional arrays. What I would like to do is sort by the first value then sort by the second value while keeping the first value sorted. See example:
arrayToSort = [[1,5],[1,3],[1,2],[1,6],[2,6],[1,9],[1,11]];

I would like to sort this so it returns

[[1,2],[1,3],[1,5],[1,6],[1,9],[1,11],[2,6]];

I have created* a function to sort the array by the first value using the function below but im unsure how exactly i can achieve the above.
function sortOne(cards){
    arr = cards.sort(function(a,b) {
        return a[0] > b[0];
    });
    return arr;
}

*source: How to sort 2 dimensional array by column value?

A: Sort by the first value, then by the second:
data.sort(function(a, b) {
    return a[0]-b[0] || a[1]-b[1];
});

It's just two (standard number) comparisons, linked by the || operator which returns the right operand when the first is 0.
See here for a generic comparison function that deals with arrays of arbitrary length, not only tuples.


text:
Q: Depending on the parameter p in C, find all solutions (in complex numbers) In the title it's $p \in \mathbb{C}$
$\begin{cases}
x+py-z=3 \\
px+y-z=9 \\
x+y-pz=1 \\
\end{cases}$
I decided to use Cramer's rule
$det_m=\begin {bmatrix}
1&p&-1 \\
p&1&-1 \\
1&1&-p \\
\end {bmatrix}=p^3-3p+2=(p-1)^2(p+2)\neq0 \Rightarrow (p\neq1 \land p\neq-2)$
1 solution for $p \in \mathbb{C} \setminus \{1,-2\}$
$det_x=9p^2-4p-5=0 \ $ it's equal $0$ only for $p=1$
$det_y=3p^2-10p+7=0 \ $ equal $0$ only for $p=1$
$det_z=-p^2+12p-11=0 \ $ equal $0$ only for $p=1$
infinity of solutions for $p=1$
no solution for $p=-2$
So if I understand this correctly, all I have to do is to write answer:
$x=\frac{9p^2-4p-5}{p^3-3p+2}$
$y=\frac{3p^2-10p+7}{p^3-3p+2}$
$z=\frac{-p^2+12p-11}{p^3-3p+2}$
where $(p \neq 1 \land p\neq-2)\land p\in \mathbb{C}$
Did I solve this assignment correctly?

A: Hint: Plugging $$z=x+py-3$$ in the second equation we get
$$(p-1)(x-y)=0$$

A: Cramer's rule is indeed a good idea here.
The relevant data is
\begin{align*}
\det\left[\begin{array}{rrr}
1 & p & -1 \\
p & 1 & -1 \\
1 & 1 & -p
\end{array}\right] &= {\left(p + 2\right)} {\left(p - 1\right)}^{2} \\
\det\left[\begin{array}{rrr}
3 & p & -1 \\
9 & 1 & -1 \\
1 & 1 & -p
\end{array}\right] &= {\left(9 \, p + 5\right)} {\left(p - 1\right)} \\
\det\left[\begin{array}{rrr}
1 & 3 & -1 \\
p & 9 & -1 \\
1 & 1 & -p
\end{array}\right] &= {\left(3 \, p - 7\right)} {\left(p - 1\right)} \\
\det\left[\begin{array}{rrr}
1 & p & 3 \\
p & 1 & 9 \\
1 & 1 & 1
\end{array}\right] &= -{\left(p - 1\right)} {\left(p - 11\right)}
\end{align*}
So, for $p\neq -2$ and $p\neq 1$, the solution to $A\vec{x}=\vec{b}$ has coordinates
\begin{align*}
x_1 &= \frac{9 \, p + 5}{{\left(p + 2\right)} {\left(p - 1\right)}} & x_2 &= \frac{3 \, p - 7}{{\left(p + 2\right)} {\left(p - 1\right)}} & x_3 &= -\frac{p - 11}{{\left(p + 2\right)} {\left(p - 1\right)}}
\end{align*}
Now, we solve the system for $p=-2$ and $p=1$. Here, the relevant information is
\begin{align*}
\operatorname{rref}\left[\begin{array}{rrr|r}
1 & -2 & -1 & 3 \\
-2 & 1 & -1 & 9 \\
1 & 1 & 2 & 1
\end{array}\right] &= \left[\begin{array}{rrr|r}
1 & 0 & 1 & 0 \\
0 & 1 & 1 & 0 \\
0 & 0 & 0 & 1
\end{array}\right] \\
\operatorname{rref}\left[\begin{array}{rrr|r}
1 & 1 & -1 & 3 \\
1 & 1 & -1 & 9 \\
1 & 1 & -1 & 1
\end{array}\right] &= \left[\begin{array}{rrr|r}
1 & 1 & -1 & 0 \\
0 & 0 & 0 & 1 \\
0 & 0 & 0 & 0
\end{array}\right]
\end{align*}
Here, we find that the system is actually unsolvable for $p=-2$ and $p=1$.


text:
Q: Making R package work in both Windows and Linux I have written a very basic package in R. In fact, I followed this tutorial for creating a basic package.
My package works just fine in linux. eg:

> install.packages("linmod", repos=NULL)
Warning in install.packages("linmod", repos = NULL) :
  argument 'lib' is missing: using '/home/jpgoel/R/i486-pc-linux-gnu-library/2.9'
* Installing *source* package 'linmod' ...
** R
** data
** preparing package for lazy loading
** help
*** installing help indices
 >>> Building/Updating help pages for package 'linmod'
     Formats: text html latex example
** building package indices ...
* DONE (linmod)
> library(linmod)
> data(mod1)
> mod1
Call:
linmod.default(x = x, y = y)

Coefficients:
     Const        Bwt
-0.3566624  4.0340627

Now, I took my "linmod" folder, copied it to Windows XP, and tried the following:

> install.packages("C:\\Documents\ and\ Settings\\foo\\Desktop\\linmod",repos=NULL)
Error in gzfile(file, "r") : cannot open the connection
In addition: Warning messages:
1: In unzip(zipname, exdir = dest) : error 1 in extracting from zip file
2: In gzfile(file, "r") :
  cannot open compressed file 'linmod/DESCRIPTION', probable reason 'No such file or directory'
>

Okay. So then I took that folder and placed it into a .zip file. Then I went to Packages -> Install package(s) from local zip files... and selected my package.

> utils:::menuInstallLocal()
updating HTML package descriptions

> library(linmod)
Error in library(linmod) : 'linmod' is not a valid installed package

I'm stumped. My package doesn't have any native code (eg, no extensions written in C.)
Feel free to download the .zip from here (the link to download is all the way at the bottom, "Save file to your PC")

A: You can't just zip up the directory from linux. You need to build specifically for Windows. I've put some instructions here. However, if you are developing on some other platform first, then Dirk's solution is simpler.

A: Consider using the excellent CRAN Win-Builder service to turn your R package sources into an installable zip file for Windows.
You simply upload by ftp, and shortly thereafter get notice about your package.

A: If the package is rather simple, the following function works for me on Windows for a package "MY_PACKAGE_1.0.tar.gz" generated with R (OS: Ubuntu with the command R CMD build MY_PACKAGE)
install.packages("MY_PACKAGE_1.0.tar.gz", repos=NULL, type="source")

The option type="source" is necessary, otherwise it does not work.